I am having some trouble passing a JSON encoded php array to javascript in Laravel 4. I am sending it to my view from my controller, populating a value field in HTML, and then pulling that value with JS. Code is below:
Controller:
$artist_likes_profile = Fanartist::profile_fan_likes(Auth::user()->get()->id);
$artist_likes = json_encode(array("name"=>$artist_likes_profile));
return View::make('artists.show', compact('artist'))
->with('artist_likes', $artist_likes);
HTML:
<input type="hidden" id="js-helper-artist-likes" name="js-helper-artist-likes" value="<? php echo $artist_likes ?>">
JS:
var artist_likes = $('#js-helper-artist-likes').val();
console.log(artist_likes);
However, running this, I only see the artist_likes variable in the console appear as "{" instead of the actual json string.
When I add these two lines (to try to decode the json variable in js):
var artist_likes_decoded = $.parseJSON(artist_likes);
console.log(artist_likes_decoded);
I get the error:
Uncaught SyntaxError: Unexpected end of input
I know the JSON string is populating the value field, because I see this in the page source:
<input type="hidden" id="js-helper-artist-likes" name="js-helper-artist-likes" value="{"name":[{"id":215,"fbid":"19538277626","stage_name":"311","city":"","state":"","image_path":"http:\/\/graph.facebook.com\/19538277626\/picture?width=720&height=720",
"description":"311 was formed in 1990 in Omaha, Nebraska."},{"id":18,"fbid":"14591271531","stage_name":"Beck","city":"","state":"","image_path":"https:\/\/graph.facebook.com\/14591271531\/picture?width=720&height=720",
"description":""},{"id":47,"fbid":"137029526330648","stage_name":"Disclosure","city":"","state":"","image_path":"https:\/\/graph.facebook.com\/137029526330648\/picture?width=720&height=720","description":""},
{"id":11,"fbid":"152513780224","stage_name":"Arcade Fire","city":"","state":"","image_path":"https:\/\/graph.facebook.com\/152513780224\/picture?width=720&height=720","description":""}]}">
Any ideas what I"m doing wrong? Thank you.
It's because JSON string contains quotas (") and that breaks html parsing. You need to escape those first.
<?php echo str_replace('"', '\"', $artist_likes) ?>
Alternative solution is to pass JSON directly to js variable if this hidden input is only to make value available for js.
var artists_likes_decoded = <?php echo $artist_likes ?>
Related
This question already has an answer here:
Print JSON with PHP, without making multiple roots and making it pretty
(1 answer)
Closed 5 years ago.
My website takes in text messages as input, and I want to store these messages in "messages.json" on the server. Every time somebody enters a new message, I simply want to append messages.json with one more entry.
As of now, I can get the user's message ($message) properly sent to "save-message.php", but I couldn't find a way to properly add that $message string into messages.json in the correct format. One issue I was running into when experimenting with json_encode($message) was I could add the elements themselves to the file, but not inside the outer JSON brackets and with a comma after all them except the last one, etc.
Note: If solution requires a call to a JavaScript function, could you show how to adjust the HTML form and the PHP code accordingly to?
Here is my HTML form I am using:
<form action="/save-message.php" method="POST">
<textarea name="message" placeholder="Enter your anonymous message here!"></textarea>
<input id="submitNoteButton" type="submit" value="Submit mystery note"/>
</form>
</div>
Current save-message.php that can properly save strings to a .txt file:
<?php
$file = 'messages.txt';
$message = $_POST['message'];
file_put_contents($file, $message, FILE_APPEND | LOCK_EX);
header('Location: /note_submitted.html'); // Redirect
?>
Goal JSON:
{"messages": [
{"message":"This is what somebody would enter"},
{"message":"This is what somebody else would enter"}
]}
One way to do it would be to decode the existing JSON string into a PHP array and add the new message(s) to it. Then just encode it again and overwrite the existing file:
<?php
// Used as an example. Replace with file_get_contents();
$json = '{"messages": [ {"message":"This is what somebody would enter"}, {"message":"This is what somebody else would enter"} ]}';
// Decode the json string to a PHP array
$decode = json_decode($json, true);
// Push the new data to the array. Used an example here
// Just replace "This is a test" with $_POST['message'];
array_push($decode['messages'], array("message" => "This is a test"));
// To see the result as an array, use this:
echo "<pre>";
print_r($decode);
echo "</pre>";
// Encode the array back to a JSON string
$encode = json_encode($decode);
// To see the result, use this:
echo $encode;
// Put it back in the file:
file_put_contents("messages.json", $encode, LOCK_EX);
?>
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); ?>
I have a database form on a MySql table on which I have a javascript function to populate the options of a select tag. Those options are fetched from a table of clients who have a status of either "Active" or "Inactive", and the return values are of those clients where their status is active. In the event an order is loaded where the client status is inactive, I'm trying to add a handler for inactive clients. The form loads from a php script that left joins the client table to the main table, where clientId in the main table is equal to Id in the client table. So, I have the name and id of the client fetched outside of the function to populate the options list, regardless of their status.
There is one line that is causing me fits. I have searched this site and others and have found many solutions, but none have worked for me so far. This is the line:
var txt = <?php echo $row[`clients`.'name']; ?> ;
What is returned in Chrome and Firefox debuggers is, "Uncaught syntax error: Unexpected token <". The debugger shows: var txt = <br />
I've tried enclosing the php script in single quotes, double quotes, and without quotes, and still no luck. Any thoughts, anyone?
About an hour later--> I found a workaround. I tried all of your suggestions, but none worked in this instance. var_dump and json_encode confirmed what I knew already, that the returned data was valid. Regardless of any of the variations in syntax, they all returned the same error. What I did was to apply the same syntax as above, but in a hidden input:
<input type="text" id="cName" hidden value="<?php echo $row[`clients`.'name']?>" />
Then changed the javascript code to this:
var txt = document.getElementById('cName').value;
Everything else works perfectly. Of course, I still have lingering thoughts about the use of backticks, and would prefer that I had a better, and safer code. As I mentioned somewhere, I simply copied the sql syntax directly from phpMyAdmin. In this instance, if I substitute single quotes for the backticks, the input returns nothing. Well, thanks all. If anyone wants to contribute more, I'll be glad to hear about it.
That's illegal PHP syntax, and very dangerous syntax in general. Try doing a var_dump($row) to see exactly what's in that array. Probably you want something more like
var txt = <?php echo json_encode($row['clients.name']); ?>;
instead.
Note the use of json_encode(). This will ENSURE that whatever you're spitting out in the JS code block is actually syntactically valid javascript.
e.g. consider what'd happen if you ended up with
var txt = Miles O'Brien;
^^^^^--undefined variable;
^--- another undefined var
^--- start of a string
^^^^^^^---unterminated string.
with json_encode(), you end up with
var txt = "Miles O'Brien";
and everything's a-ok.
var txt = "<?php echo $row['clients']['name']; ?>";
var txt = <?php echo $row[`clients`.'name']; ?> ;
Consider how PHP parses this:
var txt = is to be output directly to the client.
Enter PHP mode.
echo the following expression.
Evaluate $row[`clients`.'name'].
First we need to determine the array index, which is the concatenation of `clients` and 'name'.
Backtick in PHP is the execution operator, identical to shell_exec(). So PHP attempts to execute the shell command clients, which probably fails because that isn't what you intended and it doesn't exist. Consequently, at this stage, PHP outputs an HTML error message, starting with a line break <br />.
Your client now has var txt = <br /> (you can verify this by inspecting the HTML source of the page returned to your browser), which it attempts to evaluate in its JavaScript context. This gives rise to the "unexpected token" error that you have witnessed.
As others have mentioned, you probably meant to do something like $row['clients']['name'] or $row['clients.name'] instead—but without seeing the rest of your PHP, it's impossible to be sure. Also, as #MarcB has observed, you need to be certain that the resulting output is valid JavaScript and may wish to use a function like json_encode() to suitably escape the value.
The error comes from the fact that your return value (a string in javascript) must be in quotes.
Single quotes will take whatever is between them literally, escapes (like \n ) will not be interpreted, with double quotes they will.
var txt = "<?php echo $row['clients']['name']; ?>";
is what you want
Change this
var txt = <?php echo $row['clients'.'name']; ?> ;
to this:
var txt = <?php echo $row['clients']['name']; ?> ;
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); ?>);
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!).