NOTE: this was a completely different question until I realized where the problem really was.
My current issue is that I am trying to output some JSON from PHP for use by jQuery. I am doing this cross-domain so I am using "JSONP". I have narrowed the problem down to the fact that there are single quotes in my JSON so when I output with the callback function I end up getting too many single quotes.
I have tried calling str_replace("'","\'",$value) in PHP and it seems to output as \\' in my JSON rather than \' which is apparently not readable by jQuery (though online JSON validators say the JSON is valid.
So what I need to know is how to get only a single slash in my string inside of PHP rather than 2 slashes.
What I'm gathering is this:
jQuery uses _ as a callback parameter to JSONP requests. It will automatically append ?_=jQuery<random_numbers> basically telling the server to call this unique function name when it returns. As such, as of recently (within the last year I want to say) .ajax takes care of making a callback function for you, then kind of "re-routes" it to a function you specify within the success property.
Also, your PHP code is using $_GET['callback'] when it now should be using $_GET['_'] (to stay more in-line with jQuery and what it's sending).
The "jQuery was not called" is just jQuery notifying you that anticipated callback wasn't included in the response, and it was looking to make sure it was getting called.
Short answer (as I see it) reference $_GET['_'] instead of $_GET['callback'] to satisfy jQuery.
try to use this in your PHP:
echo $_GET['callback'] . '(' . json_encode($your_array_data) . ')';
Regards.
Related
I have a json_encoded array which is fine.
I need to strip the double-quotes on all of the keys of the json string on returning it from a function call.
How would I go about doing this and returning it successfully?
Thanks!
I do apologise, here is a snippet of the json code:
{"start_date":"2011-01-01 09:00","end_date":"2011-01-01 10:00","text":"test"}
Just to add a little more info:
I will be retrieving the JSON via an AJAX request, so if it would be easier, I am open to ideas in how to do this on the javascript side.
EDITED as per anubhava's comment
$str = '{"start_date":"2011-01-01 09:00","end_date":"2011-01-01 10:00","text":"test"}';
$str = preg_replace('/"([^"]+)"\s*:\s*/', '$1:', $str);
echo $str;
This certainly works for the above string, although there maybe some edge cases that I haven't thought of for which this will not work. Whether this will suit your purposes depends on how static the format of the string and the elements/values it contains will be.
TL;DR: Missing quotes is how Chrome shows it is a JSON object instead of a string. Ensure that you have Header('Content-Type: application/json; charset=UTF8'); in PHP's AJAX response to solve the real problem.
DETAILS:
A common reason for wanting to solve this problem is due to finding this difference while debugging the processing of returned AJAX data.
In my case I saw the difference using Chrome's debugging tools. When connected to the legacy system, upon success, Chrome showed that there were no quotes shown around keys in the response according to the debugger. This allowed the object to be immediately treated as an object without using a JSON.parse() call. Debugging my new AJAX destination, there were quotes shown in the response and variable was a string and not an object.
I finally realized the true issue when I tested the AJAX response externally saw the legacy system actually DID have quotes around the keys. This was not what the Chrome dev tools showed.
The only difference was that on the legacy system there was a header specifying the content type. I added this to the new (WordPress) system and the calls were now fully compatible with the original script and the success function could handle the response as an object without any parsing required. Now I can switch between the legacy and new system without any changes except the destination URL.
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/
I want to create my own JSON API with PHP and I want that the user can send Text to my API, especially one or more Links. So the Problem is, that this call could look something like this (in a worse case)
http://www.my.site/test.php?link[]=http://stackoverflow.com/?as=2&bs=2&link[]=http://stackoverflow.com/?af=2&bf=2
The problem is, that I get only a shorter link without the last information (here: bs=2 and bf=2).
This information is threated as GET data. How can I fix this? Must I use any escaping here?
Use urlencode:
echo 'http://www.my.site/test.php?link[]=' .
urlencode('http://stackoverflow.com/?as=2&bs=2') . '&link[]=' .
urlencode('http://stackoverflow.com/?af=2&bf=2')
You should use the urlencode PHP's function.
http://fr.php.net/manual/en/function.urlencode.php
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
I'm playing with the flickr api and php. I want to pass some information from PHP to Javascript through Ajax. I have the following code:
json_encode($pics);
which results in the following example JSON string:
[{"id":"4363603591","title":"blue, white and red...another seattle view","date_faved":"1266379499"},{"id":"4004908219","title":"\u201cI just told you my dreams and you made me see that I could walk into the sun and I could still be me and now I can't deny nothing lasts forever.\u201d","date_faved":"1259987670"}]
Javascript has problems with this, however, due to the unescaped single-quote in the second item ("can't deny").
I want to use the function json_encode with the options parameter to make it strip the quotes, but that's only available in PHP 5.3, and I'm running 5.2 (not my server). Is there a fast way to run through the entire array and escape everything before encoding it in Json? I looked for a way to do this, but it all seems to deal with encoding it as the data is generated, something I cannot do as I'm not the one generating the data.
If it helps, I'm currently using the following javascript after the ajax request:
var photos = eval('(' + resptxt + ')');
Have you considered using JSON2 instead of eval()? Details here.
str_replace('\'', '\\'', json_encode($pics))
You'll have to do a (recursive) foreach to walk through the array and manipulate them manually. You can do a str_replace, but addslashes works just as fine (and addcslashes is even better.)