Search code examples
jqueryajaxgethttp-request

Multiple Ajax HTTP GET Requests with Different Input Variables using jQuery


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?


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.