0

I have loop that cycles through multiple asynchronous AJAX calls. The call is fed the loop iteration as an index. When the call is completed, the data is stored in an array depending on the index.

However, the index returned in the success function is different than the index fed to the initial AJAX call. Is there a good way for the call to return the same index upon success that the call was initially fed?

var ptype = 'fp';
    var pnum = 2;
    var data = new Array();

    for(var i = 1; i <= 5; i++){
        call_general_forecast(ptype,i,pnum);
    }  

function call_general_forecast(ptype, i1, pnum1){
        index = pnum1*5 + i1;
        $.ajax({
             url: '',
             data : { stock_name : stock_name, pattern: ptype, specificity : i1},
             type : 'get', //or 'post', but in your situation get is more appropriate,
             dataType : 'json',
             success : function(r) {
                data[index] = r;
                alert(index);
             },
             async: true

        });          
} 
1
  • If you must run multiple AJAX calls in parallel you can pass the index to your server and have it returned as part of the result. Commented Oct 5, 2013 at 13:45

1 Answer 1

1

You're using index as a global var. Declare it as a local variable using the var keyword, and closure will do the rest for you. All success functions will have the correct index (with the same value they had when the request was being made).

function call_general_forecast(ptype, i1, pnum1){
    var index = pnum1*5 + i1;
    $.ajax({
         url: '',
         data : { stock_name : stock_name, pattern: ptype, specificity : i1},
         type : 'get', //or 'post', but in your situation get is more appropriate,
         dataType : 'json',
         success : function(r) {
            data[index] = r;
            alert(index);
         },
         async: true

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

1 Comment

You nailed it. Thanks! I'd up vote you, but I need 15 rep points -_-

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.