How to get all php array index from javascript? - javascript

I have a php file where I saved all language string. This is the content:
function lang($phrase)
{
static $lang = array(
'step_one' => 'First step',
'step_two' => 'Second step',
... and so on ...
);
return $lang[$phrase];
}
Essentially, when I load a javascript file I want store all array index in a variable like this:
var Lang = <?php echo json_encode(lang()); ?>;
this code line is inserted in a script, this script is available in a php file. Now before of execute this line I have imported the php file where all string translation is available. What I'm trying to achieve, is get all index of this array, in the variable Lang.
Actually I can load a single string traduction from php like this:
lang('step_one');
but how I can save this array in javascript variable?

You can use array_keys to retrieve all array keys. To do that you need your function to return the whole array on request. You can do that with leaving the argument ($phrase) empty and do an if condition with empty in your lang function. You also need to set a default value for $phrase in your function to not raise any errors if you don't pass an argument to the function.
echo json_encode(array_keys(lang());
And the function:
function lang($phrase = "")
{
static $lang = array(
'step_one' => 'First step',
'step_two' => 'Second step',
... and so on ...
);
if(empty($phrase)) {
return $lang;
} else {
if(isset($lang[$phrase])) { //isset to make sure the requested string exists in the array, if it doesn't - return empty string (you can return anything else if you want
return $lang[$phrase];
} else {
return '';
}
}
}
I also added isset to make sure the requested element exists in your language array. This will prevent raising warnings.

Related

Fill Array of string with interface inforamtion in angular 6

i need to fill Fill Array of string with interface inforamtion .
i send server request for return list of role with this code :
public GetRoleClaim(id:number):Observable<string[]>{
return this.http.get<string[]>('https://localhost:44390/api/Role/GetRoleClaims/'+id,{headers: this.headers}).pipe(
tap(Claims => this.log("fetch claims")),
catchError(this.handleError('Error GetRoleClaim', []))
);
}
it work correct .
after this i give data from component with this code :
this.roleService.GetRoleClaim(this.roleId).subscribe((data)=>{
this.selectedRole=data
},
(error)=>
swal('خطا',`هنگام دریافت اطلاعات خطایی رخ داده . لطفا با پشتیبانی تماس بگیرید`,'error')
);
. now i need fill this varible selectedRole:string[]; with claimValue .
the claimValue recive from server .
how can i do this ?
Firstly, this.claims should be an array of Claims, since data variable in your code is also an array of Claims.
"claims" variable definition will look like this, if you had globally defined it in your .ts file.
claims: Claims[] = [];
Now, you can just write a for loop to fill selectedRole variable.
for (const value of this.claims) {
selectedRole.push(value.claimValue);
}
Assuming selectedRole is defined locally. If it is defined globally then the above code will look like this:
for (const value of this.claims) {
this.selectedRole.push(value.claimValue);
}

Error in cookie law info plugin for Wordpress

I've got a problem with one of my plugins.
The log files said:
PHP Warning: stripslashes() expects parameter 1 to be string, array given in /mnt/web008/c1/24/57250724/htdocs/WordPress_01/wp-content/plugins/cookie-law-info/php/shortcodes.php on line 125
It looks like that there is an aray given but a string expected? I dont know how i can fix this.
/** Returns HTML for a standard (green, medium sized) 'Accept' button */
function cookielawinfo_shortcode_accept_button( $atts ) {
extract( shortcode_atts( array(
'colour' => 'green'
), $atts ) );
// Fixing button translate text bug
// 18/05/2015 by RA
$defaults = array(
'button_1_text' => ''
);
$settings = wp_parse_args( cookielawinfo_get_admin_settings(), $defaults );
/*This is line 125:*/ return '' . stripslashes( $settings ) . '';
}
Well, the error itself is pretty self explanatory.
The function stripslashes expects its parameter to be a string. A quick look at the Wordpress documentation suggests that the return value of wp_parse_args is an array, meaning the $settings variable is an array not a string and therefore passing it as an argument in stripslashes causes your error.
You can use stripslashes on an array, however, it requires a little bit more work. Here's the example given in the PHP documentation.
<?php
function stripslashes_deep($value) {
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
// Example
$array = array("f\\'oo", "b\\'ar", array("fo\\'o", "b\\'ar"));
$array = stripslashes_deep($array);
// Output
print_r($array);
?>
https://developer.wordpress.org/reference/functions/wp_parse_args/
http://php.net/manual/en/function.stripslashes.php
EDIT: It's probably worth noting that stripslashes_deep will return an array. If this is not the desired output then wrap the call the stripslashes_deep function via the implode function to convert it to a string.
implode(stripslashes_deep($settings))

Perform "javascript/jQuery-like" functions using PHP

I'm trying to move some processing from client to server side.
I am doing this via AJAX.
In this case t is a URL like this: https://itunes.apple.com/us/podcast/real-crime-profile/id1081244497?mt=2&uo=2.
First problem, I need to send a bunch of these URLs through this little function, to just pull out "1081244497" using my example. The following accomplishes this in javascript, but not sure how to make it loop in PHP.
var e = t.match(/id(\d+)/);
if (e) {
podcastid= e[1];
} else {
podcastid = t.match(/\d+/);
}
The next part is trickier. I can pass one of these podcastid at a time into AJAX and get back what I need, like so:
$.ajax({
url: 'https://itunes.apple.com/lookup',
data: {
id: podcastid,
entity: 'podcast'
},
type: 'GET',
dataType: 'jsonp',
timeout: 5000,
success: function(data) {
console.log(data.results);
},
});
What I don't know how to do is accomplish this same thing in PHP, but also using the list of podcastids without passing one at a time (but that might be the only way).
Thoughts on how to get started here?
MAJOR EDIT
Okay...let me clarify what I need now given some of the comments.
I have this in PHP:
$sxml = simplexml_load_file($url);
$jObj = json_decode($json);
$new = new stdClass(); // create a new object
foreach( $sxml->entry as $entry ) {
$t = new stdClass();
$t->id = $entry->id;
$new->entries[] = $t; // create an array of objects
}
$newJsonString = json_encode($new);
var_dump($new);
This gives me:
object(stdClass)#27 (1) {
["entries"]=>
array(2) {
[0]=>
object(stdClass)#31 (1) {
["id"]=>
object(SimpleXMLElement)#32 (1) {
[0]=>
string(64) "https://itunes.apple.com/us/podcast/serial/id917918570?mt=2&uo=2"
}
}
[1]=>
object(stdClass)#30 (1) {
["id"]=>
object(SimpleXMLElement)#34 (1) {
[0]=>
string(77) "https://itunes.apple.com/us/podcast/real-crime-profile/id1081244497?mt=2&uo=2"
}
}
}
}
What I need now is to pull out each of the strings (the URLs) and then run them through a function like the following to just end up with this: "917918570,1081244497", which is just a piece of the URL, joined by a commas.
I have this function to get the id number for one at a time, but struggling with how the foreach would work (plus I know there has to be a better way to do this function):
$t="https://itunes.apple.com/us/podcast/real-crime-profile/id1081244497?mt=2&uo=2";
$some =(parse_url($t));
$newsome = ($some['path']);
$bomb = explode("/", $newsome);
$newb = ($bomb[4]);
$mrbill = (str_replace("id","",$newb,$i));
print_r($mrbill);
//outputs 1081244497
find match preg_match() and http_build_query() to turn array into query string. And file_get_contents() for the request of the data. and json_decode() to parse the json responce into php array.
in the end it should look like this.
$json_array = json_decode(file_get_contents('https://itunes.apple.com/lookup?'.http_build_query(['id'=>25,'entity'=>'podcast'])));
if(preg_match("/id(\d+)/", $string,$matches)){
$matches[0];
}
You may have to mess with this a little. This should get you on the right track though. If you have problems you can always use print_r() or var_dump() to debug.
As far as the Apple API use , to seperate ids
https://itunes.apple.com/lookup?id=909253,284910350
you will get multiple results that come back into an array and you can use a foreach() loop to parse them out.
EDIT
Here is a full example that gets the artist name from a list of urls
$urls = [
'https://itunes.apple.com/us/podcast/real-crime-profile/id1081244497?mt=2&uo=2.',
'https://itunes.apple.com/us/podcast/dan-carlins-hardcore-history/id173001861?mt=2'
];
$podcast_ids = [];
$info = [];
foreach ($urls as $string) {
if (preg_match('/id(\d+)/', $string, $match)) {
$podcast_ids[] = $match[1];
}
}
$json_array = json_decode(file_get_contents('https://itunes.apple.com/lookup?' . http_build_query(['id' => implode(',', $podcast_ids)])));
foreach ($json_array->results as $item) {
$info[] = $item->artistName;
}
print '<pre>';
print_r($info);
print '</pre>';
EDIT 2
To put your object into an array just run it through this
foreach ($sxml->entries as $entry) {
$urls[] = $entry->id[0];
}
When you access and object you use -> when you access an array you use []. Json and xml will parse out in to a combination of both objects and arrays. So you just need to follow the object's path and put the right keys in the right places to unlock that gate.

Extra slash comes in json array

I works on nestable drag and drop. When I drag and drop tiles It generate an array in textarea which is [{},{"id":267},{"id":266}]. Now When I post this array in action page then It posted [{},{\"id\":267},{\"id\":266}]. Why this extra slash comes in array. In action page I convert this array using json_decode. Now How I remove this slash from array or how I ignore this array that I successfully decode this array through jsondecode.
$(document).ready(function()
{
var updateOutput = function(e)
{
var list = e.length ? e : $(e.target),
output = list.data('output');
if (window.JSON) {
output.val(window.JSON.stringify(list.nestable('serialize')));//, null, 2));
} else {
output.val('JSON browser support required for this demo.');
}
};
// activate Nestable for list 1
$('#rightservices').nestable({
group: 1
})
.on('change', updateOutput);
// output initial serialised data
updateOutput($('#rightservices').data('output', $('#siteservices')));
//$('#nestable3').nestable();
});
Sounds like Magic Quotes is set on the server. This is an old, deprecated, feature of PHP where any request data would be automatically escaped with slashes regardless of what is was. You can follow the instructions listed here to disable them. From that page, any of these should work, depending on what you have access to:
In php.ini
This is the most efficient option, if you have access to php.ini.
; Magic quotes for incoming GET/POST/Cookie data.
magic_quotes_gpc = Off
In .htaccess
If you don't have access to php.ini:
php_flag magic_quotes_gpc Off
At runtime
This is inefficient, only use if you can't use the above settings.
<?php
if (get_magic_quotes_gpc()) {
$process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
while (list($key, $val) = each($process)) {
foreach ($val as $k => $v) {
unset($process[$key][$k]);
if (is_array($v)) {
$process[$key][stripslashes($k)] = $v;
$process[] = &$process[$key][stripslashes($k)];
} else {
$process[$key][stripslashes($k)] = stripslashes($v);
}
}
}
unset($process);
}
?>
The below will remove the first object in the array but doesn't really solve the real issue of why it is being added in the first place?
var arr = [{},{\"id\":267},{\"id\":266}];
arr.splice(0,1);

How to Build a jQuery array and move to the php, then use it on a PHP Function?

$(".divclass").each(function() {
Build An Array with all .divclass ID (
});
~~~~> POST with AJAX for page.php
PHP gets the array and then use the function with each result of #divclassID
require "phpfunction.php";
$array = array received from AJAX;
for each #divclassID => $key {
getFunction($key)
}
After, rebuild a json array and print this;
Text explication:
1º) For each .divclass, Build an array with all $(this).attr("ID"); (with ID of each .divclass)
2º) Send the array to page.php;
3º) page.php receives the array and use the phpfunction with each element ID Listed in array;
Please, It's possible?
Create one page for client-side and write some jQ Code in your page:
$(function(){
var ids = [];
$(".divclass").each(function() {
ids.push($(this).attr('id')); // Push into JS array
});
$.post('page.php',{ids:ids},function(){
alert('Horay, the data sent');
});
});
page.php:
<?php
require "phpfunction.php";
$ids = $_POST['ids']; // The $ids contains array of ID as you expected
?>
is simple alright ? Do you ?

Categories

Resources