Using and retrieving PHP variables within JSON - javascript

I've just started using JSON to throw around information between pages and I simply can't figure this one out.
Basically, I have one page that's using jquery getJSON to get some JSON data from another page. But the PHP variables won't/can't get replaced with the necessary content.
Here's the jquery script (which is working fine I believe)
$.getJSON("./menu-controller.php", { editId: getEditId, getEditInfo: true },function(data) {
console.log(data);
var id = data.itemId;
alert(id);
});
I can get it to work just fine when using this code on the other page
$json = '{ "itemId":"4" }';
echo $json;
HOWEVER, if I use this, then it won't work
$menuId = 4;
$json = '{ "itemId":$menuId }';
echo $json;
So my question is, how can I get $menuId to actually replace itself with the number and come back on the other page correctly?
I've tried messing with the quotes and re-arranging the quotes for 4 hours. It either comes up with an error or it doesn't replace $menuId with the actual number.

You should make a PHP array instead and then convert it to JSON.
For instance:
$array = array();
$array['itemId'] = $menuId;
echo json_encode($array);
Note: there is also a json_decode function that takes in a JSON string and converts it into PHP as well. You might find that useful.

FYI, PHP variables are interpolated in double quotes only and not in single quotes. So, you've to do something like this:
$json = "{ \"itemId\":$menuId }";
echo $json;
Please see the demonstration over here: http://codepad.viper-7.com/CDC0oM

In this sample:
$menuId = 4;
$json = '{ "itemId":$menuId }';
echo $json;
You have wrapped your JSON string in single quotes. PHP substitutes values in double quotes, so the value is not substituted here, and the vale you echo is
{ "itemId":$menuid } - this is not valid JSON.
You're better off creating a PHP array and using json_encode() to create the SON string:
echo json_encode(array("itemId"=>$menuId));

The problem is that you've enclosed your PHP variable within single (rather than double) quotes, so PHP isn't looking in the string for variables to replace.
So this should work:
$json = "{ \"itemId\": $menuId}";
As well as the json_encode method suggested by Cezary Wojcik (which is going to be a lot more flexible if the data gets more complex!).

Related

Print PHP JSON encoded array, to JavaScript and decode it, produces errors

I have to use some data from PHP to JavaScript. I am using JSON for that. I encode the array with PHP's json_encode function and then I want to decode it with JavaScript.
<?php
$data = array(
"..."=>"...",
.....
);
?>
<script>
var data = jQuery.parseJSON('<?php echo json_encode($data); ?>');
console.log(data);
</script>
The problem is sometimes produces errors in javascript console on parsing the JSON, most of times when $data contains HTML.
How can I print a json encoded code inside javascript, dinamically with PHP?
Thank you!
JSON is in fact JavaScript Object Notation, it can be echoed directly in a variable, and doesn't need parsing.
var data = <?= json_encode($data); ?>;
The errors will typically come from when the data contains ' (which prematurely terminate your string literal) or new line characters (which get parsed by the JS parser and render the JSON invalid).
You could get around this by explicitly escaping such characters (with a string replacement function run on the generated JSON), but that is more effort than is worth going to.
Since JSON is a subset of the JavaScript literal syntax, you can just treat it as JavaScript directly. You don't need to wrap it in a string and then parse that string to the JS data structure.
var data = <?php echo json_encode($data); ?>

div innerhtml not taking html

I want to update innerhtml of div with id NotifyDiv
I want to change it with following html code.
$html="<ul id='js-news'><li>HELLO WORLD!</li></ul>";
I am using following code to change it.
echo "<script>document.getElementById('NotifyDiv').innerHTML='$html'</script>";
But no changes occur.
However it I remove id = 'js-news' from the above ul tag it works.But I'll need the id.
If you check the source code of your browser you will see this:
<script>document.getElementById('NotifyDiv').innerHTML='<ul id='js-news'><li>HELLO WORLD!</li></ul>'</script>
So we can see that in the JavaScript string you are using apotrophes, but the string is already encloded with apostrophes, so it attempts to end the string early: (before the letter j in js-news)
'<ul id='js-news'><li>HELLO WORLD!</li></ul>'
This can be solved by using escaped quotation marks for the JS string:
echo "<script>document.getElementById('NotifyDiv').innerHTML=\"$html\"</script>";
Basically, the code you have causes a syntax error in JS:
echo "...innerHTML='$html'</script>";
expands to:
// opening ' closing ' => js-news === syntax error!
// \/ \/
echo "...innerHTML='<ul id='js-news'><li>HELLO WORLD!</li></ul>'</script>";
Resulting JS code:
document.getElementById('NotifyDiv').innerHTML='<ul id='js-news'><li>HELLO WORLD!</li></ul>'
The syntax highlighting shows the problem
Note the single quotes around $html and the single quotes inside the $html string. The best way to echo PHP values in JS would be to use json_encode:
echo "...document.getElementById('NotifyDiv').innerHTML=", json_encode($html), "</script>";
The output should be something like:
<script>document.getElementById('NotifyDiv').innerHTML="<ul id='js-news'><li>HELLO WORLD!<\/li><\/ul>"</script>
Now, those slashes are escaped, and you probably don't want that. Thankfully, there's a second parameter you can pass to json_encode: cf the docs. Passing JSON_UNESCAPED_SLASHES is what you need to do here:
$html="<ul id='js-news'><li>HELLO WORLD!</li></ul>";
echo "<script>document.getElementById('NotifyDiv').innerHTML=".json_encode($html, JSON_UNESCAPED_SLASHES)."</script>";
The output:
<script>document.getElementById('NotifyDiv').innerHTML="<ul id='js-news'><li>HELLO WORLD!</li></ul>"</script>
DEMO
Perfect ans to your query is as under (just copy n paste and check it)
<?php
$html="<ul id='js-news'><li>HELLO WORLD!</li></ul>";
?>
<script type="text/javascript">
document.getElementById('NotifyDiv').innerHTML="<?php echo $html; ?>";
</script>";
You need to pass PHP variable with PHP syntax that is <?php ?>
Even if we can mix PHP, JavaScript and HTML together, we need to initialize proper languages before using their variables in case of JavaScript and PHP.
So, final code should be:
echo "<script>document.getElementById('NotifyDiv').innerHTML = '<?php echo $html;?>'</script>";
Otherwise, everything looks correct.

Generate JSON array

I want to generate a JSON array with PHP, but it doesn't work well.
My PHP array looks like this:
protected $resultArray = array("1.0" => 0, "1.3" => 0);
then I do this:
return json_encode($resultArray);
but then i've got this:
var array = [{"1.0":2,"1.3":1}];
Why is " replaced with "?
quot; is a quote character (") encoded as HMTL. json_encode() does not produce HTML encoded sequences.
Replace return with echo in return json_encode($resultArray); and you'll see this for yourself.
Most probably the returned string is passed further to a function that runs it through htmlspecialchars() or htmlentities() and this is the correct way to work with it if you put it into an HMTL context.
Use a different viewer class if you need to output only the json_encode()-ed string. I don't know TYPO3 but I guess you should use JsonView; pass it $resultArray as-is and it will call json_encode() for you.
I think you may using etended library for example in wamp server I tested this code and it's work fine
$str = "<div style='position:relative'><img src='/assets/ui/success.png' /><span
style='position:relative;top:-15px;'>Nachricht empfangen!</span></div>";
echo json_encode(array('prompt' => $str));
//output
//{"prompt":"<div style='position:relative'><img src='\/assets\/ui\/success.png' \/><span style='position:relative;top:-15px;'>Nachricht empfangen!<\/span><\/div>"}
Thanks guys for help!
The solution is (only for typo3). To get a properly correct JSON-Array in the view the JS code has to be improved the following way:
var array = {f:format.htmlentitiesDecode(value:chartarray)};

Sending PHP Strings Variables to a Javascript String Variables

Hi I am trying to send a long string of numbers from a file to Javascript. One I get it in Javascript as a string the rest will be easy.
This is the PHP code that grabs the series of numbers. It does grab them properly because it prints it out perfectly if I instruct it to do so.
$data = readfile($dataFile);
This is the Javascript Code:
var data = <?php echo json_encode($data, JSON_NUMERIC_CHECK); ?>;
When ever I run it the variable "data" is set to a random number. I assume it is the the number of characters in the sequence. I am relatively new to PHP and Javascript so a nice and clear explanation would be greatly appreciated. Thanks in advance.
Readfile reads the contents of the file and outputs them. It returns the byte length of the file, so $data is the number of the read bytes. link.
The number that is set in the variable $data is the number of bytes read by readfile. This is because readfile only reads the file and outputs its content to the standard output. To get the actual data in the file and assign it to a viariable, you can use file_get_contents(), like this:
$data = file_get_contents($dataFile);
Then the javascript assignment is good ;)
You need quotes if you want it to be a string in Javascript:
var data = '<?php echo json_encode($data, JSON_NUMERIC_CHECK); ?>;';

pass php array of email addresses to javascript

I have a php array containing email addresses that needs to be passed to a javascript function, but when javascript is trying to handle the addresses, i am getting a syntaxerror: illegal character error relating to the '#' in the email addresses...
How can I get round this? Is there a way of converting the email addresses to strings prior to them being passed to javascript? Or would I need to iterate over the array once it has been passed to js, and create a new array in js and convert them to strings then?
Ok, so the array is created by the user selecting the emails addresses from a list using checkboxes, this is then posted to a second page.
Heres the php code to create the array on the first page:
while ($row = mysqli_fetch_array($students_results)) {
echo'<div class="form-group"><div class="checkbox"><label><input type="checkbox" name="parentsemails[]" value=' . $row['parent_email'] . '">' . $row['parent_name'] . ' (Student: '. $row['student_name'] . ')</label></div></div>';
}
This is then posted to a seond page to be passed to the js function. The php to assign the array to a php variable is:
if (isset($_POST["parentsemails"])) {
$pe = $_POST['parentsemails'];
}
The the JS code inside the function:
email_a = new array(<?php echo implode(',', $pe); ?>);
The email addresses appear to be passed to JS correctly, in the error log I can see the individual emails, but with the illegal character highlighted...
Any help appreciated.
Thanks.
You are not enclosing the e-mails in quotes, which causes the syntax error you are getting.
You can add the quotes manually, but you can use the json_encode function instead.
The json_encode encodes a PHP object or array in JSON. As a JSON array is a valid JavaScript array, this will work well in your case.
Just change the JS line to:
email_a = <?php echo json_encode($pe); ?>;
As others have said, it looks like you need to surround the strings in quotes before putting them in the Javascript. Something like this.
<?php
$_a = array();
foreach($pe as $str)
$_a[] = "'${str}'";
?>
email_a = new array(<?php echo implode(',', $_a); ?>);

Categories