Curtis Crewe
Curtis Crewe

Reputation: 4336

How to handle Ajax JSON response?

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???
            }
        }
});

Upvotes: 5

Views: 8817

Answers (2)

softvar
softvar

Reputation: 18435

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"]);
            }
        }
});

Upvotes: 7

tymeJV
tymeJV

Reputation: 104775

You would do:

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

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

Upvotes: 6

Related Questions