Dewgong
Dewgong

Reputation: 67

jQuery - Access PHP array values after AJAX POST

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.

Upvotes: 3

Views: 883

Answers (1)

Håvard
Håvard

Reputation: 10080

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.

Upvotes: 3

Related Questions