Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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." } What am i doing wrong reading the message?

like image 547
dpegasusm Avatar asked Feb 14 '14 05:02

dpegasusm


People also ask

Can AJAX return JSON?

You couldn't directly return an array from AJAX, it must have converted in the valid format. In this case, you can either use XML or JSON format. In the tutorial demonstration, I will return an array of users from AJAX, while return converts the array into JSON format using the json_encode() function in the PHP.

How do I get AJAX response in JSON?

Approach: To solve this problem, we will first consider a JSON file named “capitals. json” and try to get this JSON data as a response using AJAX. Then we will create an HTML file “capitals. html” which contains a table which we will use to populate the data we are getting in response.

How can I get specific data from AJAX response?

You can't as it's asynchronous. If you want to do anything with it, you need to do it in a callback. How? Because it's asynchronous, javascript will fire off the ajax request, then immediately move on to execute the next bit of code, and will probably do so before the ajax response has been received.

Can JavaScript parse JSON natively?

JSON is a JavaScript-based object/value encoding format that looks very close to raw JavaScript and can be very easily parsed by JavaScript code because JavaScript can effectively evaluate a JSON string and re-materialize an object from it.


2 Answers

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");
like image 116
Sherin Jose Avatar answered Sep 23 '22 21:09

Sherin Jose


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');
like image 43
Adesh Pandey Avatar answered Sep 23 '22 21:09

Adesh Pandey