3

I'd like to access a PHP array using JavaScript after a successful POST.

PHP Code:

return array('success' => true);

Javascript Code

$('#Get-Info').submit(function() {
$.post("info.php",
    function(data){
        if ( data['success'] ) {
            // Do things.
        }
    }
);
return false; });

The javascript function is definitely running, it just can't access the PHP array.

2
  • Are you setting a header so the content type is JSON? Also what does you response look like (is that the only thing being returned?) Commented Dec 9, 2010 at 0:40
  • I tried setting the content type to JSON, no luck. For the purpose of trying to figure out what's wrong, that is indeed the only thing being returned in the info.php file. Commented Dec 9, 2010 at 0:41

1 Answer 1

3

Make the php return json. Not sure about this part as I'm not a php programmer, but the javascript would look like this:

$('#Get-Info').submit(function() {
$.post("info.php",
    function(data){
        if ( data['success'] ) {
            // Do things.
        }
    }, "json"
);
return false; });

The only difference being that jQuery will automatically parse the data as json, the datatype parameter. More info.

If I'm not horribly wrong, this should work for the php, although it requires PHP 5.2.0:

echo json_encode(array('success' => true));

More info.

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

2 Comments

Thanks. Works great. Do you know if there's much overhead associated with using json_encode in PHP?
I can't imagine there being, but don't take my word on it. Like I said, I'm no php programmer.

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.