3

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.

1
  • Could you provide more of the Javascript you are using so we can see how it's retrieving the PHP file in question and where it's failing? Commented May 22, 2011 at 10:43

3 Answers 3

2

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);
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks Alex, you been always on my topics, in fact, I obtained data from a post response: $.post("file.php",{},function(data){/*Here I should pars the json object to act with*/});
but the problem is not solved yet, I just provided pore details about the way I received data.
@dany90 Try it on the data variable.
Wow, God how close was I, thank you Alex, you inspired me again, the solution was var obj = jQuery.parseJSON(data); alert(obj.stat); really as said, the solution is always closer than be imagine, see ya!
2

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.

Comments

0

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

1 Comment

Then may be you would like to mark the answer with some rewards :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.