简体   繁体   中英

jQuery $.post Callback Function (data) is Undefined

I submit a form using jQuery to a php file on my server. Everything works... (the php file gets the right post variables, makes a database entry etc.) But on the response, sometimes 'data' goes wacky.

$('#form_submit').click( function() {
    $.post("path/to/script.php", $('#form').serialize(), function(data) {
        if ( data.status == 1 ) {
            alert('awesome sauce');
        } else {
            alert('crap');
        }
    }, "json");
});

php script returns (on success)

$response['status'] = 1;
$response['message'] = 'worked';
echo json_encode($response);
exit();

I'm getting a whole lot of crap, and not enough awesome sauce.

Does anyone have an idea why sometimes 'data.status' is undefined, and sometimes it isn't?

Try it like this>

$('#form_submit').click( function() {
$.post("path/to/script.php", $('#form').serialize(), function(data) {
var obj = jQuery.parseJSON(data);
    if ( obj.status == 1 ) {
        alert('awesome sauce');
    } else {
        alert('crap');
    }
});
});

How does exit() behave with regards to output buffering? Does it flush the output buffer?

try this one:

$('#form_submit').click( function() {
    $.post("path/to/script.php", $('#form').serialize())
     .success(function(){
        alert('awesome sauce');
     }).error(function(){
        alert('crap');
     });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM