Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get json data from a php file

Good morning folks,

I'm just that beginner in json, I have a formated data (array) encoded and sent from a php file, the only thing I want is how to get this data and alert it to be simple??

My object sent from the php file is like: {"stat":"opened","do":"close"} I found the best way to do so, var obj = jQuery.parseJSON(???)but really can't get it work and Google does not want to help me this time !!

Edit: The json object received from a post response:$.post("page.php",{},function(data){/*Here I should pars data and act with*/});

Very glad if you support me in this issue! Regards.

like image 287
Nadjib Mami Avatar asked Mar 18 '26 10:03

Nadjib Mami


2 Answers

If you have jQuery, you just pass the JSON string to that $.parseJSON(). The return value is the native object.

var obj = jQuery.parseJSON('{"stat":"opened","do":"close"}');
console.log(obj.stat, obj.do);
like image 63
alex Avatar answered Mar 19 '26 22:03

alex


With JSON responses, you should not need to manually parse them into JavaScript objects with jQuery.parseJSON().

You can tell jQuery which data type to expect by specifying the dataType parameter to jQuery.post() (docs).

For example,

jQuery.post(
    "file.php",
    function (data) { /* data is a JS object already-parsed */ },
    "json"  // <-- tell jQuery that we expect a JSON response
);

You should really be sending along a Content-Type header from your PHP script, telling jQuery (and everything else accessing the script) that the response is JSON with the application/json content type.

like image 28
salathe Avatar answered Mar 19 '26 22:03

salathe