Error in cookie law info plugin for Wordpress - javascript

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))

Related

unable to get json data from server

My server side code is:
$bus = array(
'meaning' => $name
);
$jsonstring = json_encode($bus);
echo $_GET['callback'].'(' . $jsonstring. ')';
the value displayed on the screen is correct - ?word=heart({"meaning":"heart"})
but when I am reading it with following code its printing the value of meaning as 11200665987893779229_1460521505942
$(document).ready(function(){
$.getJSON('http://mydomain?callback=?','word=heart',function(res){
document.getElementById('print').innerText=''+res.meaning;
});
});
but when I do this:
$bus = array(
'meaning' => 'heart'
);
it's printing the correct value i.e heart
I am not getting why this is happening and how to get the correct value (I am accessing data from my different domain).
JSON.parse() converts any JSON String passed into the function, to a JSON Object.
$(document).ready(function(){
$.getJSON('http://mydomain?callback=?','word=heart',function(res){
obj = JSON.parse(res);
document.getElementById('print').innerText=''+obj.meaning;
});
});
a similar post is here

How to get all php array index from 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.

problems parsing JSON in javascript from PHP

Here is my PHP array:
$entries = array(
1420934400 => array(
'entry' => 'I think I liked it.',
'data' => 'some'
),
1452470400 => array(
'entry' => 'Turkey is much better. Tastes more like chicken.',
'data' => 'no calls'
));
Then I convert to JSON
$entries = json_encode($entries);
This produces the string:
{"1420934400":{"entry":"I think I liked it.","data":"some"},"1452470400":{"entry":"Turkey is much better. Tastes more like chicken.","data":"no calls"}}
...which I believe is valid JSON. But when I try to access in JavaScript:
<script>
var fetchedEntries = JSON.parse(<?php echo $entries ?>);
console.log('entries: %o', fetchedEntries);
</script>
I get the following error:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of
the JSON data
Can anyone see where I'm going wrong?
You don't need JSON.parse in JS since JSON can be directly interpreted by JS (it is called JavaScript Object Notation for a reason ;-). Do
var fetchedEntries = <?php echo $entries ?>;
When you receive the JSON data as a string, then JSON.parse is appropriate. For example, this works too:
var fetchedEntries = JSON.parse( "<?php echo json_encode( $array_or_obj ); ?>" );

JSON passes string instead of array or object from PHP to Javascript

I am having som trouble with passing a multidimensional and associative array from php to Javascript. I converte it with JSON, using:
_SESSION = '<?php print json_encode($_SESSION) ?>';
I have also tried
_SESSION = '<?php print json_encode($_SESSION, JSON_PRETTY_PRINT) ?>';
_SESSION = $.parseJSON('<?php print json_encode($_SESSION) ?>');
both of them give me errors like: Uncaught SyntaxError: Unexpected token ILLEGAL.
However, the first one doesn't give me any errors and I can access it in Javascript. It then outputs:
{"items":{"221163":{"CodeComplete":null,"Project":"Coding","Team":"Mail","TimeSpent":25","Children":[]}}, {"221165":{CodeComplete":null,"Project":"Coding","Team":"Batman","TimeSpent":"40","Children":[]}}
I belive this is like a string, since _SESSION[0] outputs "{". However, I want it to be an array or an object. The Array looks like this in php:
_SESSION( "items" => array(
221163 =>
array( CodeComplete => null
Project => "Coding"
Team => "Mail"
Timespent => "25"
Children => array(
)
)
221165 =>
array( CodeComplete => null
Project => "Coding"
Team => "Stones"
Timespent => "40"
Children => array(
)
)
)
)
I want to be able to access this array in the same way as I can in php (not litterary ofcorse) but _SESSION["items"] or _SESSION.items is undefined as _SESSION is a string...
Any ideas of what I'm doing wrong?
Just as #CD001 suggested in his comment, I removed the '' from the transfer so that it became
_SESSION = <?php print json_encode($_SESSION) ?>;
instead and now everything works fine, thank you!

if statement in while loop

I have a PHP script that gets some data from a table in my MySQL database.
And then it sends this information back to the PHP page with JSON javascript.
It all works great but i would like to make an if statement in the while loop.
My "used" table sends back "1" and "5" instead of echoing back 1 or 5 i want it to send Yes or NO.
One way of doing this could be breaking down the $data and replace the 1 or 5 with Yes or No.
But is there any another way of doing it?
Something like: `if (used == '1') { set used == 'No } else {set used == 'Yes' }`
my code below
while ($row = $result->fetch_assoc()) {
$data['results'][] = array(
'id' => $row['id'],
'number' => $row['number'],
'type' => $row['type'],
'code' => $row['code'],
'price' => $row['price'],
'used' => $row['used'],
'utime' => $row['utime'],
'username' => $row['username']
);
}
//Everything went to plan so set success to true
$data['success'] = true;
//Set the content type for a json object and ensure charset is UTF-8. NOt utf8 otherwise it will not work in IE (Darn IE! >.<)
header("Content-Type: application/json; charset=UTF-8");
//json encode the data and cast to an object so we can reference items like this.id in the javascript instead of this['id'] etc.
echo json_encode((object)$data);
You can use the conditional operator in the array assignment:
'used' => $row['used'] == 1 ? 'Yes' : 'No',
You can do this without if statement:
$answer = array(0 => 'No', 1 => 'Yes');
...
'used' => $answer[ $row['used'] ],
...

Categories

Resources