6

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

6
  • 2
    What is your entire ajax call? What language is your server-side script? Commented Apr 21, 2012 at 18:32
  • console.dir(outputfromserver) should tell you what outputfromserver is and then you'll know how to access it. Maybe you have to fresh up your JavaScript basics beforehand. Commented Apr 21, 2012 at 18:39
  • I am doing that console the log , but dont know how to process Commented Apr 21, 2012 at 18:42
  • It would be helpful to see your JavaScript AJAX call. Are you using $.getJSON(), or at least $.ajax() and specifying dataType as json? Commented Apr 21, 2012 at 18:47
  • You should post your whole jQuery ajax code (did you use $.get() or $.post() with "json" as the last argument or $.getJSON()?), not just the success callback, because that won't help us help you with much. Commented Apr 21, 2012 at 22:18

4 Answers 4

17

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!

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this solved my problem. I previously set my array as dataType : 'text' and js didn't recognize it
3

The array is a valid JSON string, you need to parse it using JSON parser.

success: function(outputfromserver) {
    var data = JSON.parse(outputfromserver);
    $.each(data, function(index, el) { 
        // Do your stuff
    });
},
...

3 Comments

Not really. If jQuery knows that the response is JSON (and chances are that it does know) then the JSON is automagically parsed for you. Also, There's no such thing as a "JSON Object".
can i use data[0] there to get the first element ?
Worked for me - simple solution for jquery get :-)
1

You can use JS objects like arrays

For example this way:

// Loop through all values in outputfromserver
for (var index in outputfromserver) {
  // Show value in alert dialog:
  alert( outputfromserver[index] );
}

This way you can get values at first dimension of array, above for..loop will get values like this:

// Sample values in array, case: Indexed array
outputfromserver[0];
outputfromserver[1];
outputfromserver[2];
// So on until end of world... or end of array.. whichever comes first.
outputfromserver[...];

However, when implemented this way, by using for ( index in array ) we not only grab indexed 1,2,3,4,... keys but also values associated with named index:

// Sample values in array, case: accosiated/mixed array
outputfromserver["name"];
outputfromserver["phone"];
outputfromserver[37];
outputfromserver[37];
outputfromserver["myindex"];
// So on until end of world... or end of array.. whichever comes first.
outputfromserver[...];

In short, array can contain indexed values and/or name associated values, that does not matter, every value in array is still processed.

If you are using multidimensional stuff

then you can add nested for (...) loops or make recursive function to loop through all and every value.

Multidimensional will be something like this:

// Sample values in array, case: indexed multidimensional array
outputfromserver[0][0];
outputfromserver[0][1];
outputfromserver[1][0];
outputfromserver[1][...];
outputfromserver[...][...];

Update, JSON object:

If you server returns JSON encoded string you can convert it to javascript object this way:

try { 
    // Try to convert JSON string with jQuery:
    serveroutputobject = $.parseJSON(outputfromserver); 
} catch (e) {
    // Conversion failed, result is not JSON encoded string 
    serveroutputobject = null;
}

// Check if object converted successfully:
if ( serveroutputobject !== null ) {
    // Loop through all values in outputfromserver
    for (var index in serveroutputobject) {
        // Append value inside <div id="results">:
        $('#results').append( serveroutputobject[index] + "<br/>" );
    }
}
// In my own projects I also use this part if server can return normal text too:
// This way if server returned array we parse it and if server returns text we display it. 
else {
    $('#results').html( outputfromserver );
}

More information here

3 Comments

Thanks so to access all elements , do i need to use for (var i in outputfromserver) { alert( i ); console.log( value ); }
@yyyi777 Now with bigger screen corrected some typos and added more detail, please read again as example is rewritten too.
@yyyi777 Here's small example I created: jsfiddle.net/Kw6A6 You can do tests with it to make sure if it suits for your needs. Will's answer shows great quality too.
0
$.ajax({
    type : "POST",
    dataType: "json",
    url : url,
    data:dataString,
    success: function(return_data,textStatus) {



         temperature.innerText=return_data.temp;
                   // OR
        **temperature.innerText=return_data['temp'];**  

    },
    error: function(jqXHR, textStatus, errorThrown) { 
                 alert("Error while accessing api [ "+url+"<br>"+textStatus+","+errorThrown+" ]"); return false;    
    }
 });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.