1

I declare an array then make an ajax call which returns multiple rows of values. I'm trying to add the id of these rows to that array that i declared previously, but it keeps returning undefined.

  var recipeIds = Array();
    $.ajax({
        url: url,
        type: 'POST',
        contentType: "application/json",
        dataType: 'jsonp',
        crossDomain: true,
        jsonp: 'jsoncallback',
        cache:true,
        success: function(data, status){
            $.each(data, function(i,item){
                             recipeIds.push(item.id);
         });
        },
        error: function(){
            console.log("Ajax not working - recipies in cat");
        }
    });
    alert("array0 = " + recipeIds[0]);

any suggestions?

cianBuckley
  • 1,264
  • 2
  • 18
  • 25
  • possible duplicate of [Variable doesn't get returned from AJAX function](http://stackoverflow.com/questions/12475269/variable-doesnt-get-returned-from-ajax-function) – Denys Séguret Mar 13 '13 at 16:54

1 Answers1

3

When you alert, the ajax call hasn't yet returned. It's asynchronous, meaning the ajax call will happen after the alert.

You must use the result from inside the success callback you give to the ajax function.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • oh right. thanks.i'm a bit thick sometimes! i do however need to use this variable... actually to make other ajax calls. any suggestions for a workaround? – cianBuckley Mar 13 '13 at 16:58
  • Yes, do your other calls from inside the success callback or from a function you call from the success callback. I give an example in [this answer](http://stackoverflow.com/a/12475285/263525). – Denys Séguret Mar 13 '13 at 16:59