I have a function that returns json (networks_function.php builds up some arrays and encodes them as json):
var json;
$(document).ready(function(){
$.post("network_function.php", function(data) {
json = data;
alert(json);
});
});
I pass the json variable to a new function which doesn’t interpret it correctly. However, when I copy the text of the alert statement and hard-code that into the second function (and set it equal to the json variable), it works. I’m sure this isn’t an issue with variable scope. Does anybody know why this could be?
It thinks it’s not JSON. Just tell jQuery that it’s JSON data:
The reason that copy and pasting it works is because a JSON string when pasted into a JS context is an object literal. When you alert an actual object (which is what you want to be alerting), you will see “Object” and maybe a bit of debugging information depending on the browser.
Note that you could (and should) also send json headers in your PHP file