Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle Ajax JSON response?

Tags:

json

jquery

ajax

I'm basically doing an Ajax call which returns a dynamic result each time, here's a sample of the response

[{"id":10858362988,"http_code":"200","result_code":"1"}]

How can I access the result_code? I've tried doing the following to no avail

$.ajax({
        type: "GET",
        url: window.apiURL,
        data: data,
        success: function(data) {
            var myObj = $.parseJSON(data);
            switch(myObj.result.code) {
                //this doesn't work for some reason???
            }
        }
});
like image 727
Curtis Crewe Avatar asked Aug 05 '14 19:08

Curtis Crewe


2 Answers

Since the response of the AJAX GET Request is an array, you have to access the key using index as suggested by @tymeJV.

$.ajax({
        type: "GET",
        url: window.apiURL,
        data: data,
        success: function(data) {
            var myObj = $.parseJSON(data);
            console.log(myObj[0]["result_code"]);
        }
});

If the response is an array of objects:

Something like: [{"id":10858362988,"http_code":"200","result_code":"1"}, {"id":20858362988,"http_code":"404","result_code":"1"}], do something like below

$.ajax({
        type: "GET",
        url: window.apiURL,
        data: data,
        success: function(data) {
            var myObj = $.parseJSON(data);
            for (var i=0; i<myObj.length; i++) {
                console.log(myObj[i]["result_code"]);
            }
        }
});
like image 87
softvar Avatar answered Sep 23 '22 23:09

softvar


You would do:

var code = myObj[0]["result_code"];

You have an array containing 1 object, so reference the index.

like image 28
tymeJV Avatar answered Sep 23 '22 23:09

tymeJV