简体   繁体   中英

Javascript Reading JSON result from AJAX response

I have a javascript file that makes an AJAX call to a php file on the server which returns JSON encoded data. The PHP file can return either a success or a failure depending with about a dozen different messages like so:

if ( something here ) {
    if( something else here ) {
        if( more tests here ) {
            $response['success'] = 'Successfully did something.';
        } else {
            $response['success'] = 'Successfully made this work';
        }
    } else {
        $response['error'] = 'Failed to make the donuts.';  
    }
} else {
    $response['error'] = 'I need more information!';
}
echo json_encode($response);
exit;   

I have javascript/jquery on the front end that is checking for the response failure condition and displaying an alert box and performing some other relevent actions depending.

$.post(ajaxurl, data, function(response) {
    if( response.hasOwnProperty("success") ) {
        if( $(this).is( ":checked" ) ) {
            $(this).removeAttr( "checked" );
        } else {
            $(this).attr( "checked", "true" );
        }
        alert( response["success"] );
    } else {
        alert( "Sorry, something went wrong.  \nError: " + response["error"] );
    }
});

The problem is that no matter how i check for the success condition it always displays the error message with a response['error'] of undefined I've tried testing for typeOf response['success'] != "undefined" and a number of other ways to see if the success value is set but nothing seems to work. I am getting a response that when I console.log it looks like so: { "success", "Successfully did something." } { "success", "Successfully did something." } What am i doing wrong reading the message?

You need to parse JSON response before use,

$.post(ajaxurl, data, function(response) {
    var response=JSON.parse(response);
    //then your code
});

OR

You can use the datatype property as json in the AJAX call like:

$.post(ajaxurl, data, function(response) {
     //your code
}, "json");

Simply Edit your code of the JavaScript by adding Data Type in the end (see last parameter in the following code snippet) please refer https://api.jquery.com/jQuery.post/

$.post(ajaxurl, data, function(response) {
    if( response.hasOwnProperty("success") ) {
        if( $(this).is( ":checked" ) ) {
            $(this).removeAttr( "checked" );
        } else {
            $(this).attr( "checked", "true" );
        }
        alert( response["success"] );
    } else {
        alert( "Sorry, something went wrong.  \nError: " + response["error"] );
    }
},'json');

Well, the guys above have given the answer, but I have found one more problem in your code:

I guess this post statement is invoked in a event handler of a checkbox and you want to modify the status of this checkbox after response. But the this object is no longer the checkbox in the post callback function, it's the post object. So you'll find your code won't change the status of checkbox after response as you expected.

Your can modify your code like this:

var $ele = $(this);
$.post(url, data, function() {
...
if( $(this).is( ":checked" ) ) {
            $ele.removeAttr( "checked" );
        } else {
            $ele.attr( "checked", "true" );
        }
...
}, "json");

Edit:

Well, the code above is not elegant enough for introducing an unnecessary local variable and the callback function has to keep the local variables of the parent function in memory(as a result of closure), so the following is a better choice:

$.post(url, data, $.proxy(function() {
...
//use "this" object just like the original code of author
...
}, this), "json");

Use the dataType parameter in your ajax call and set it to json. And by the way, you can just do:

alert( response.success );

Since the returned object from ajax call or the "data" callback parameter is actually a json object, not an array.

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