How to Access Array response of AJAX

javascript, jquery

Solution

It would help to know what your AJAX request looks like. I recommend using $.ajax() and specifying the dataType as JSON, or using $.getJSON().

Here is an example that demonstrates $.ajax() and shows you how to access the returned values in an array.

$.ajax({
    url: 'test.json', // returns "[1,2,3,4,5,6]"
    dataType: 'json', // jQuery will parse the response as JSON
    success: function (outputfromserver) {
        // outputfromserver is an array in this case
        // just access it like one

        alert(outputfromserver[0]); // alert the 0th value

        // let's iterate through the returned values
        // for loops are good for that, $.each() is fine too
        // but unnecessary here
        for (var i = 0; i < outputfromserver.length; i++) {
            // outputfromserver[i] can be used to get each value
        }
    }
});

Now, if you insist on using $.each, the following will work for the success option.

success: function (outputfromserver) {

    $.each(outputfromserver, function(index, el) {
        // index is your 0-based array index
        // el is your value

        // for example
        alert("element at " + index + ": " + el); // will alert each value
    });
}

Feel free to ask any questions!

Problem

This is my AJAX call response which is in array format [1,2,3,4,5,6] ``` success: function(outputfromserver) { $.each(outputfromserver, function(index, el) { }); ``` How can we access outputfromserver all values ?? Means outputfromserver Zeroth value is 1 , 2nd element is 2 , -----so on

Original source