0

My application performs multiple ajax requests, to do this I call a function 'send' with a set of parameters. On success I still want to use the original set of parameters however the next ajax request may have changed these, which will result in errors. see the code below.

Example: If request A calls the send function with an index of 0, I want that index to still be 0 when i use it in the success block. however by the time Request A is successful request B has changed it to 1 for its own ajax call.

can anyone recommend the best way to maintain the original value corresponding to each request and stopping the change?

code that calls 'send' note that the iterator i is the index I mentioned in my example

        makeGithubRequest: function (url, callback, action) {

        //if not a stat api dataset then perform one manual call
        if(action == "commit" || action == "star"){
            darwin.githubModule.send(url[0] + darwin.projectManagerModule.getcurrRequestPage(), callback, 0, action);
        } else {
            //if a stat api then loop each url, only send true callback on final url
            for(i=0;i<url.length;i++){

                //only perform actually call back when all request data collected
                if(i==(url.length-1)){
                    darwin.githubModule.send(url[i] + darwin.projectManagerModule.getcurrRequestPage(), callback, i, action);
                } else {
                    darwin.githubModule.send(url[i] + darwin.projectManagerModule.getcurrRequestPage(), darwin.projectManagerModule.noCallBack, i, action);                 
                }   
            }
        }
    },

the 'send code'

var darwin = darwin || {};

darwin.githubModule = (function() {

return {
    send: function (url, callback, index, action) {     
        $.ajax({
              dataType: 'JSON',
              type : "GET",
              url : url,
              headers : {
                  Accept: "application/vnd.github.v3.star+json"
              },
              beforeSend: function(req) {
                  req.setRequestHeader('Authorization', 'Basic ' + btoa('xxxxx'));
              },
              success : function(response) {  
                  darwin.Mediator.performSuccessAction(action, response, callback, index);                    
              },
              error: function() {
                $('#ajaxGetUserServletResponse').text("An error occured when connecting to the API, make sure the url is correct");
                $("#ajaxGetUserServletResponse").css({"opacity":"1"});   
             }
        });
    }
};
})();
user3904388
  • 103
  • 8
  • *Example: If request A calls the send function with an index of 0, I want that index to still be 0 when i use it in the success block. however by the time Request A is successful request B has changed it to 1 for its own ajax call.* Huh. That actually surprises me. Because the success function is declared as a closure here, it should be inheriting only the calling-context variables from that particular `send` call, rather than one universal static `index`/`action`. I'd kind of like to debug this code in-depth but I suppose that's not an option. – Katana314 Dec 01 '15 at 15:28
  • I updated my question with some more code details, hopefully that helps! – user3904388 Dec 01 '15 at 15:44
  • Your code should already do what you are requesting. index is a number, and therefore is NOT being passed by reference, so there's no possible way future requests could be changing it. – Kevin B Dec 01 '15 at 19:22
  • i will rephrase :) the change is a result of 'Request B' calling send with a different index value before the first call hits success, so when request A finally hits success it is taking parameter value of Request B and passes that on, not the original one passed in. Basically on the success block it is taking the parameter index value, which sometimes get overridden by a new call to send. I think I am covering old group with this comment, but hopefully this clarification makes thing clearer, Somehow I need to protect the original value of the passed in index so I can refer to it in success. – user3904388 Dec 01 '15 at 19:28
  • *"Basically on the success block it is taking the parameter index value, **which sometimes get overridden by a new call to send**."* but... that isn't possible for numbers passed as a parameter to a function. – Kevin B Dec 01 '15 at 19:29
  • Hmm really strange, I will need to investigate further. must be something im missing, ran myself ragged on this issue! – user3904388 Dec 01 '15 at 19:31
  • Is it possible `darwin.Mediator.performSuccessAction` could somehow be the cause? no idea what that is. – Kevin B Dec 01 '15 at 19:35
  • If you replaced your for loop with a forEach loop, it would completely rule out the index changing even further. – Kevin B Dec 01 '15 at 19:37
  • I am beginning to suspect its may be that the second request may be finishing before the first, which would explain the error im getting later down the process chain. if i think thats the case I will close this question, everyones time is very much appreciated. – user3904388 Dec 01 '15 at 19:54

2 Answers2

0

You could use a closure, e.g:

send: function (url, callback, index, action) {
    (function (url, callback, index, action) { // redefining variables locally
        $.ajax({
            dataType: 'JSON',
            type: "GET",
            url: url,
            headers: {
                Accept: "application/vnd.github.v3.star+json"
            },
            beforeSend: function (req) {
                req.setRequestHeader('Authorization', 'Basic ' + btoa(xxx'));
            },
            success: function (response) {
                darwin.Mediator.performSuccessAction(action, response, callback, index);
            },
            error: function () {
                $('#ajaxGetUserServletResponse').text("An error occured when connecting to the API, make sure the url is correct");
                $("#ajaxGetUserServletResponse").css({
                    "opacity": "1"
                });
            }
        });
    })(url, callback, index, action); // passing variables
}
Community
  • 1
  • 1
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
  • hi, I tired this code. sadly the problem is still occurring. It is really bamboozling! having read into closures a bit more I figured this would solve it, but it is not the case – user3904388 Dec 01 '15 at 15:38
  • @user3904388 It depends maybe how do you call `send()` method too. – A. Wolff Dec 01 '15 at 15:40
  • I will include the logic for that in my question shortly, i updated my question to show the whole file and see if theres anything I didn't consider an issue that might be causing the problem. – user3904388 Dec 01 '15 at 15:41
0

I am posting this answer in case anyone else happens upon a similar scenario and mistakens the cause like I did. The problem was a result of a secondary request finishing before the initial request, to resolve the issue I just tweaked some prior logic. Hopefully this helps anyone who sees similar behaviour.

Thanks for Everyone who gave there time to assist me.

user3904388
  • 103
  • 8