2

I have a problem returning/processing JSON data while calling $.get() function. Here's the code:
JQuery:

$.get("script.php?",
        function(data) {
            if (data.status) {
                alert('ok');
            } else {
                alert(data.error);
            }               
    },'json');

PHP

if ($r) {
    $ret = array("status"=>true);
} else {
    $ret = array("status"=>false,"error"=>$error);
}
echo json_encode( $ret );

So this is the code. But the response is always taken as string in the jquery. data.status and data.error is undefined.

2 Answers 2

4

Your PHP script needs to set the Content-type header of the response to application/json, e.g.:

header('Content-type: application/json');

Alternately, you can tell jQuery that's going to get JSON back by using the dataType option. Or just use getJSON, which does exactly that. :-)

Edit Sorry, just noticed: You are passing the dataType parameter to get. My suggestion is to look carefully at the response text: Is it really valid JSON? (This site can help there.) From your quoted PHP it seems like it should be, but if there were any other output before or after...

Sign up to request clarification or add additional context in comments.

Comments

1

You need to use jQuery 1.4.x, otherwise you have to parse the returned data by yourself.

data = JSON.parse(data);

1 Comment

thanks! I'll have to dwnld the latest jquey to make things easier

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.