Nadjib Mami
Nadjib Mami

Reputation: 5830

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.

Upvotes: 3

Views: 2321

Answers (3)

salathe
salathe

Reputation: 51950

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.

Upvotes: 2

Rizwan Sharif
Rizwan Sharif

Reputation: 1119

In your php file , you should also set header('Content-type: application/json');

Upvotes: 0

alex
alex

Reputation: 490263

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);

Upvotes: 2

Related Questions