Question

I want to make asychronous get requests and to take different results based on the input that I provide to each one. Here is my code:

param=1;
$.get('http://localhost/my_page_1.php', param, function(data) {
   alert("id = "+param);
   $('.resul   5.t').html(data);
});

param=2;
$.get('http://localhost/my_page_2.php', param, function(data) {
   alert("id = "+param);
   $('.result').html(data);
});

The result for both requests is: "id = 2" I want the results to be: "id = 1" for the 1st request, and "id = 2" for the second one..

I want to do this for many requests in one HTML file and integrate the results into the HTML as soon as they are ready.

Can anyone help me to solve this problem?

Was it helpful?

Solution

Because your calls are asynchronous, the callbacks do not execute until all of the above lines have already run. This means param will be set to the value 2 before your first get request resolves.

Create unique names for your variables like param1, param2, instead of just reassigning param.

Edit:

Check out this code:

    for (var i = 0 ; i < 3; i++) {
        param = i;
        $.get('http://www.google.com',genCallback(param));
        param = i+5;
    }

    function genCallback(param) {
        var cb = function (data) {
            alert(param);
        }
        return cb;
    }

Honestly, I'm not really sure how it works. You'll notice it alerts the number 0, 1, 2 in some order, even though I'm constantly changing param. Instead of creating an anonymous function in the get directly, I create a function based on the parameter. What I think happens is a closure is created over cb which includes the local param of genCallback at the time it executes.

OTHER TIPS

When you call an AJAX function, the callback of that request is handled out of synch with the rest of your code. The function specified to be called when the request is finished isn't called before... the request is finished.

This is how your code most often (due to the asynchronous nature of AJAX) would work:

  1. You set param = 1 and send the first ajax request
  2. You set param = 2 and send the second ajax request
  3. First get call is finished. The callback for this call is processed. Your param variable is now 2
  4. Second get call is finished. The callback for this call is processed. Your param variable still 2

The solution would be to have different variables for each call or to increment param and send the second ajax call inside the callback function of the first one.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top