printing a PHP string and parsing it as a JSON in javascript - php

I have a json_string in my database.
I echo and parse it to an object in javascript
I do
$.parseJSON('<?php echo $json_string;?>');
I get a json parse error.
What should I be doing?
This is my json_String
{"patches":[[{"diffs":[[1,"\u000a\u000a printhellon() {\u000a\u000a\u000a}d\u000a\u000a\u000a"]],"start1":0,"start2":0,"length1":0,"length2":26}],[{"diffs":[[0,") {\u000a\u000a\u000a}d"],[1,"s"],[0,"\u000a\u000a\u000a"]],"start1":15,"start2":15,"length1":11,"length2":12}],[{"diffs":[[0," {\u000a\u000a\u000a}ds"],[1,"d"],[0,"\u000a\u000a\u000a"]],"start1":16,"start2":16,"length1":11,"length2":12}]],"times":[1314489779299,1314489779408,1314489779581]}

I think JSON parsers don't like line breaks in strings for some reason. Parsing worked for me after removing the \u000a characters.
Edit: just like Brad said, it would be better to include the code directly as an object. Parsing JSON is usually more useful for data obtained using Ajax or something.

From your example, it appears like you're trying to insert PHP code into your javascript. You can't use PHP like that. PHP is server side, while Javascript runs in the browser after the page has been downloaded.
If you must get data from PHP to your javascript, you need to use AJAX. It's actually really easy with JQuery. Check out http://api.jquery.com/jQuery.ajax/

Related

how to remove backslashes in json URL with php

i need to remove () backslash in my string when using echo json_encode()?
my example..
$song_url = 116e9155e0afc11555cf33dc9c9bd25d.mp3
$resmsg[] = array("Song_name"=>"$song_name","Song_URL"=>"http://www.kbmusique.com/songs/$song_url");
echo json_encode($resmsg);
my output is
[{"Song_name":"djigh araouioui","Song_URL":"http:\/\/www.kbmusique.com\/songs\/116e9155e0afc11555cf33dc9c9bd25d.mp3"}]
but i need as
[{"Song_name":"djigh araouioui","Song_URL":"http://www.kbmusique.com/songs/116e9155e0afc11555cf33dc9c9bd25d.mp3"}]
Is there a way to solve this? Thank you.
Your comment indicates that you just need to get a copy/pastable URL for testing.
Just parse the JSON and extract the piece of data you need from it. i.e. If you want a text representation of something, then convert the JSON to text, don't try to hack the JSON into a specific form.
You could do this in PHP with json_decode, in a browser with JSON.parse(), or just use a tool such as the Chrome JSONView extension.

Difference between echoing json_encode and returning it in ajax

I think this may be classified as basic but I was curious. Why do you have to parse json encoded data returned from ajax calls but not if it is echoed by php in the main loading document?
Edit: Basically the question is, if I have an object called data with a property id in both cases, why I can type
data.id
and have the value returned when the json object has been echoed out while loading the main document, but have it throw an error when returned from an ajax call and not parsed?
By echoed, I assume you mean you did something like this:
<script>
var data = <? echo json_encode($data) ?>;
alert(data.id);
</script>
If that's the case, the browser knows that the echoed json is code because it's contained by script tags. JSON is a subset of JavaScript, so what you're really doing here is generating JavaScript code that the browser then interprets.
Ajax, on the other hand is different. When you load something with ajax, it might be text, xml, csv, html, svg, or any of dozens of different formats. JSON is just a data format like all the others I listed, so you've got to tell the javascript engine what it is. That's why you have to parse it. It needs to know the format of the text so it can interpret it correctly.
You don't have to, and JSON-encoded strings still need to be "decoded" from Javascript. It's just a faster way of being able to access array elements/properties in the returned string for ajax calls.

Clean php output into javascript

Due to the nature of my project. I am pulling data from my db and outputting to javascript. Things were working just fine till I got to the main content. It has strings like (;, :, - ''). How do I ensure that these are displayed without crushing my script coz as for now nothing seems to work.
If all you have is a single string value then see answer by Tomalak Geret'kal.
If there is any chance of getting something more than a single value from your database, like an array, object, null, or anything more complex, then I would suggest using json_encode. By using something like this:
<script>
var your_JavaScript_variable = <?php echo json_encode(your_PHP_variable); ?>;
</script>
you can pass complex data structures, arrays, or even single strings from PHP to JavaScript with all of your backslash escaping done automatically.
Additionally when you use JSON for moving your data from PHP to JavaScript it will be easy to make your application get the data from your server asynchronously without page refreshes using AJAX in the future.
You can use the PHP addslashes function for inserting into Javascript, and htmlspecialchars for inserting into HTML.
You should be encoding that data into json. PHP has a handy function to do this, json_encode.
Be sure to use the JSON_HEX_QUOTE option or the quotes in your data will break your js.
Read this: http://php.net/manual/en/function.json-encode.php

JSON concept with javascript & PHP

I need someone to shed some light on this subject.
When a person do an AJAX call, that call a php script which echo out json_encode stuff, so that the javascript can mess around with it. Note: Assuming we set the header to json in the php script.
The data that the javascript receive from the php script, do we have to parse it using eval or json's library? Edit: Is it because it treats the data recieved from the php file as text and not as javascript?
Can we use the javascript dot-notation on the data that the php script returned? Or does this data have to some how be converted to a javascript object before we can use dot-notation?
Thank you in advance.
JSON is merely a string, which happens to conform to Javascript's syntax for objects (hence the abbreviation: JavaScript Object Notation.)
To convert it to a Javascript object, you can use the eval function, but for greater security, it's recommended to use the JSON object included in modern browsers, or a function provided by your Javascript library of choice:
var json = '{"thing":1, "thang":"two"}';
var obj1 = eval('('+json+')'); // easier, less secure
var obj2 = JSON.parse(json); // secure, but doesn't work everywhere
var obj3 = jQuery.parseJSON(json); // secure, works everywhere
Many libraries will also handle the conversion for you as part of the Ajax request. Here's how jQuery does it:
jQuery.get('http://domain.com/path/to/request', function(obj)
{
// string is automatically converted to an object,
// usable as array or with dot notation
alert(obj.thing);
alert(obj['thang']);
},
'json'); // indicates that we are requesting json and not html
You can always use a library like jQuery, Mootools, Prototype, etc. for the decoding JSON text to Javascript variables..
JSON is something like serialize from PHP :) It's a way to transform string to object and back :)

Php's json_decode and firefox's javascript compatibility

it appears if you have something like
var my_var = {"foo" : "bar"};
in javascript (with firefox at least) and post it to a php server you will receive a string like
{foo:"bar",}
on the server side. But json_decode in php doesn't like the trailing ',' or the lack or quotes around 'foo'. Is there a nice way to clean up the received json string?
The json object is sent with the drupal module json services.
EDIT: This question can be closed. The badly formed json is due to badly written js in the drupal module
What code are you using to POST the data? Make sure you're using something like json2.js.

Categories