passing php string of JSON ( with qoutes) to onclick function - javascript

I'm trying to pass an array of data from php to java script for "onclick" event.
I do it by converting the array data into JSON string in order to parse it back in the js function and work on it.
The problem is that JSON string contains double quotes , so it arises an error as the double quotes break the html string (Uncaught SyntaxError: Unexpected token ILLEGAL ). I did see several questions similar to this, but didn't find a solution to what I need, or maybe I didn't understood the correct solution. So I bring it up here with my specific case.
<?php
..some php code here..
$aData = array("You","Me",76,array(3,6));
$sJSONstr = json_encode($aData);
?>
<input type="button" name="formSubmit" value="Delete" onclick="analyze('<?php echo $sJSONstr; ?>')">
<?php
..some php code here..
?>
and the js function is as follows:
function analyze(i_sInputDataJSONStr)
{
var aInputData = JSON.parse(i_sInputDataJSONStr);
.. So something with the input data array..
}

Use single quotes for the onclick attributes instead of double quotes. Single quotes is equally valid as double quotes.
One more thing, since you already have your data in JSON format, there is no need to put it as a string in the analyze function call, since your JSON data is a valid JavaScript array (that's what JSON stands for: JavaScript Object Notation).
Therefore, you don't have to parse the input string in your analyze function declaration.
Consider the following example, this is perfectly valid code.
<?php
$arr = ["Hello", "World"];
$json = json_encode($arr); // $json = '["Hello","World"]'
?>
<div id="myDiv" onclick='doSomething(<?php echo $json; ?>)'>Click me</div>
<script type="text/javascript">
function doSomething(data){
for (var i = 0; i < data.length; i++) {
alert(data[i]);
}
}
</script>

create a javascript string and pass it:
<script type="text/javascript">
var myjson = '<?php echo $sJSONstr; ?>';
</script>
and then:
onclick="analyze(myjson)"

<input type="button" name="formSubmit" value="Delete" onclick='analyze(<?php echo $sJSONstr?>)'>
Replace the double quotes with single quotes in onclick='';
Worked like a charm for me.

Related

How to pass a JavaScript array into an inline function call generated by PHP

I have build a dynamic list from an array and must print the onclick event inline, I don't know of anyway other way to do this.
<?php
$dataArray = $_POST['dataArray']; // This is a valid array
ECHO '<div id="colorSelectorBox">';
for ($btn = 0; $btn < sizeof($dataArray); $btn++){
ECHO '<div class="btn-group">
<button onclick="buildGroupList("'.$dataArray.'")">' .$dataArray[$btn].'</button>
<button><div ..Stuff..></div></button>
</div><br>';
}
ECHO '</div>';
?>
The problem is that the JavaScript function buildGroupList() does not receive an array from this instead the line looks like this in my developer tool:
onclick="buildGroupList(Array)"
How can I pass in an array of values through to JavaScript?
OR
How can I re-write this so that the call is not inline?
The shortest answer is: use json_encode() which will convert the array to a json string, but it's not good practice anyway.
Because you are trying to print the array as if automagically transforms itself into javascript array, that is, a string of its values separated by a comma (that is what it needs to output to the html, something the browser understands).
For that you need implode:
string implode ( string $glue , array $pieces )
Join array elements with a $glue string.
ECHO "<div class=\"btn-group\">
<button onclick=\"buildGroupList(['".implode("','",$dataArray)."'])\">" .$dataArray[$btn]."</button>
<button><div ..Stuff..></div></button>
</div><br>";
It takes every element in the array and puts $glue string between every one of them. The end result looks like this:
//let's assume this is your array in PHP
<?php
$dataArray = array('one','two','three');
?>
<!-- then your HTML looks like this -->
<button onclick="buildGroupList(['one','two','three'])">...</button>
Remember that PHP and Javascript don't know each other.

Proper way to escape json data in PHP without using JS comment hack

Consider the code below to send a json string to js from php,
<?php
$str = "<!--<script>"; // This is from user input
?>
<script>
var json_str = <?= json_encode($str) ?>;
</script>
The string will break the HTML, and the way to solve it is via something like the old school comment hack, e.g.
<script>
<!--
var json_str = <?= json_encode($str) ?>;
//-->
</script>
Are there any alternative?
You can use the flag JSON_HEX_TAG, so that < and > will be encoded as \u003C and \u003E respectively.
json_encode($str, JSON_HEX_TAG)

How To Escape a PHP Variable in Javascript?

I am trying to create a Javascript function that echoes out a Wordpress function called the_title() which just returns the title of the a blog. Through PHP it echoes out fine but when I do it through Javscript, however, quotes seem to be unescaped (specifically single quotes). Any help or explanation why this is happening?
THE CODE:
function createSliderTabs() {
var para = document.createElement("li");
var strings = "<?php the_title(); ?>";
var post_string = strings.replace(/"/g, "").replace(/'/g, "").replace(/\(|\)/g, "");
var node = document.createTextNode(post_string);
para.appendChild(node);
var element = document.getElementById("control-navigation");
element.appendChild(para);
}
createSliderTabs();
THE RESULT:
Macy&#8217 ;s Herald Square (had to include space or it would've changed to single quote)
WHAT IT SHOULD BE:
Macy's Herald Square
Any help or guidance on why this is happening? Thx in advance...
From php to js transformation you always have to use json_encode().
to avoid xss
to describe unicode characters
You can use html_entity_decode:
I'm not really familiar with wordpress, but I suppose you would use it inside the_title():
function the_title()
{
$str = 'Macy’s Herald Square';
echo html_entity_decode ($str, ENT_COMPAT , "UTF-8");
}
If you need to use json_encode() you should be able to do
$json = html_entity_decode(json_encode($array), ENT_COMPAT , "UTF-8");
EDIT: added ENT_COMPAT , "UTF-8"

passing PHP arrays to javascript with JSON

Okay so I know this has been asked before and I've tried the solutions, but for some reason they don't work for me so I'm asking for some help. I haven't used JSON yet so maybe it's something silly but I have no clue...
Here's the code:
<?php
$array;
#successful attempt to display array with json_encode in php
echo json_encode($array);
?>
<html>
<input id="show" type="button" onclick="showArray()" value="showArray">
<divShow>
</divShow>
<script>
function showArray(){
var array = <?php echo json_encode($array); ?>;
//Failed attempt to display array in the div field show
document.getElementById("divShow").appendChild(array);
//Failed attempt to display the array with an alert.
for(var i=0; i<2; i++){
alert(array[i]);
}
};
</script>
</html>
So what do you guys think? Am I missing something? Is it possible that the array was successfully passed to javascript but for some reason won't show?
Thanks,
-Alex
EDIT:
So I'm getting a series of arrays from a text file. I use these arrays as strings to display on the page and then convert them to float arrays. When I echo one of the float arrays such as $Z_Ausmass with:
echo json_encode($Z_Ausmass);
I get [25.39999961853,121.48651123047]. However, when I use the following to display the array through javascript:
function calc(){
var Z_Ausmass = <?php echo json_encode($Z_Ausmass); ?>;
for(var o=0; o<Z_Ausmass.length; o++){
var textnode = document.createTextNode(Z_Ausmass[o]);
document.getElementById("divCalc").appendChild(textnode);
}
};
it does not work. It's vital I get the float arrays in the script because the script needs to make calculations based on them and then display the calculations to the user.
When i execute the code it works ok.
The first attempt fails because you can't append the complete array. You need to append each element in the array seperately.
The second attempt works correctly. You only need to remove the first attempt to make it work because the first attempt stops the execution of the javascript.
edit
I tried to fix the code for you. I used a simple array with only text.
The element you wanted to show in did not have the id you where referencing to
<divShow></divShow>//wrong
<div id="divShow"></div>//right
to loop trough the complete array you do not want to hard code the max # of elements use arr.length as max for the 'for'-loop.
You can't directly append raw text to an html element. You need to make a TextNode of it and then append that node to the html element.
var textnode=document.createTextNode(arr[i]);
document.getElementById("divShow").appendChild(textnode);
So The working code will be something like this:
<?php
$array = array("test","text","show");
#successful attempt to display array with json_encode in php
echo json_encode($array);
?>
<html>
<input id="show" type="button" onclick="showArray()" value="showArray">
<div id="divShow">
</div>
<script>
function showArray(){
var arr = <?php echo json_encode($array); ?>;
//Put the text in a text node, append to the div
for(var i=0; i< arr.length; i++){
var textnode=document.createTextNode(arr[i]);
document.getElementById("divShow").appendChild(textnode);
}
};
</script>
</html>

error trasfering php array to javascript

I have this array:
$men['display']=array(
"edit" =>"1",
"description" =>"2",
"phone" =>"3",
"mail" =>"4"
);
I tried to transfer it to javascript by using:
<?php $disArray = json_encode($men['display']);?>
then, I sent it to javascript:
<select id="selectBoxHere" onChange="loadInnerHTML('<?php $disArray ?>')";>
For some reason, my javascript function 'loadInnerHTML' dosen't send my array to javascript.
You forget the echo statment.
And if you use single quotes, it makes this a string. For a javascript object you don't need the single quotes, json_encode will ensure it is javascript safe.
loadInnerHTML(<?php echo $disArray ?>)
I'd also recommend that you store this variable directly in javascript first, rather than passing it into a function. Otherwise you have to worry about double quotes inside double quotes, breaking your <select> tag.
var disArray = <?php echo $disArray ?>;
Then you can just use that variable.
loadInnerHTML(disArray)
Echoing an array in php will result in
var dis_array = Array
which js couldn't understand. Try:
var disArray = JSON.parse( '<?php echo json_encode( $disArray ) ?>' );

Categories