Escaping javascript onclick with json data - javascript

I've got a button I build with php to fire a javascript onclick event:
<button onClick='edit(this, "<?php echo $this->result[$i]["type"]; ?>","<?php echo $quality; ?>", "<?php echo json_encode($stuff); ?>", ...)">
</button>
I just added the json data $stuff. Now when I'm in javascript to get some values:
jQuery(stuff).each(function(index) {
console.log( "The key is " + this.name + " and the value is " + this.hash );
});
I get this error: SyntaxError: missing ) after argument list
This is because json data is using double quotes so the result looks something like this:
"foo", "bar", "[{"name":"test","hash":"123"},{"name":"test1","hash":"456"},..."
In this onclick event I've tried changing the quotes to single quotes or vice versa. I've tried escaping quotes with backslashes. It seems nothing works. What am I missing?

Have you tried escaping the quotes for the json that you are returning? You can do so like this:
echo json_encode($this->result[$i]["type"]);.
It will make your json like this:
\"foo\", \"bar\", \"[{\"name\":\"test\",\"hash\":\"123\"}....
If your code is already in json, json_encode() shouldn't change anything except adding the blackslashes.

... "<?php str_replace('"', '\"', $this->result[$i]["type"]); ?> ...
Maybe it's because in text you show (type) is " character.

Related

JavaScript call function with PHP-Variable as transfer parameter

I am calling the JavaScript-function getElementById. As transfer parameter I want to use the PHP-Variable $currentTab
var currentTab = document.getElementById(<?php $currentTab ?>);
You need to add quotes, and output your variable with echo. Maybe add the # character if it is not in your php variable
document.getElementById('<?php echo $currentTab; ?>');
Just add ' or " around <?php $currentTab ?>, for getElementById() accept a string. And in javascript a string is surrended by ' or ".

php variable in a javascript object within a json result

I'm trying to put a php variable within a js script that is in a result variable that will be processed with json but i don't get it to work. I know it has something to do with the "" and '' but i can't figure out what it is.
$result["html"] .= "<script type='text/javascript'>setTimeout(function () { window.location='.$config[\"BURL\"].'; }, 2500);</script>";
Edit: whoohoo i got the 15 points to upvote! Thanks u all!
You will have to concatenate strings using . and remove the escaping of the quotes for the index, like so:
$result["html"] .= "<script type='text/javascript'>setTimeout(function () { window.location='" . $config["BURL"] . "'; }, 2500);</script>";

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

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.

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 ) ?>' );

Modifying a JSON object returned with PDO

I'm trying to return use a JSON object with handlebars. Making a small todo list to learn how to use it.
My PHP API is as follows :
$query = "SELECT *
FROM table";
try
{
$db = getConnection();
$response = $db->query($query);
$todo = $response->fetchAll(PDO::FETCH_OBJ);
$bdd = null;
echo json_encode($todo);
}
It then returns something like :
[{"id":"1","todo":"Do something","who":"Me","is_done":"0"},{"id":"2","todo":"Learn JSON","who":"Me","is_done":"0"}]
But I'd actually need it to be like this :
{todos: [{"id":"1","todo":"Do something","who":"Me","is_done":"0"},{"id":"2","todo":"Learn JSON","who":"Me","is_done":"0"}]}
I tried in my PHP API to add instead of echo json_encode($todo)
echo '{todos: ' . json_encode($todo) . '}';
But it doesn't work. Any ideas ?
Your "todos" property name must be quoted with double-quote characters.
echo '{"todos": ' . json_encode($todo) . '}';
Though JavaScript syntax allows for property names without quotes, strict JSON insists on them.
While Pointy's answer is correct (might want to read about JSON), alternatively you could do this:
echo json_encode(array('todos' => $todo));
PHP associative arrays will be serialized to JSON as objects (json_encode() example in Manual).
Try with :
echo '{ "todos" : ' . json_encode($todo) . '}';
Try this:
echo json_encode(array( 'todos' => $todo ));
Instead of making the JSON yourself, make the structure you want, then have PHP make the JSON for you.

Categories