Multiple Ajax HTTP GET requests with various input variables using jQuery

I want to make asynchronous receive requests and accept different results based on the input that I provide to everyone. 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 queries: "id = 2" I want the results to be as follows: "id = 1" for the first query and "id = 2" for the second.

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

Can someone help me solve this problem?

+4
source share
2 answers

Since your calls are asynchronous, callbacks are not executed until all of the above lines have been run. This means that the parameter will be set to 2 before your first receive request is resolved.

Create unique names for your variables, such as param1, param2, instead of just reassigning the parameter.

Edit:

Check 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 quite sure how this works. You will notice that it notifies the number 0, 1, 2 in some order, although I am constantly changing the parameters. Instead of creating an anonymous function in get directly, I create a function based on a parameter. I think the closure is created over cb , which includes the local genCallback parameter at the time it is executed.

+4
source

When you call the AJAX function, the callback of this request is processed without synchronization with the rest of your code. The function specified for the call when the request is completed is not called until ... the request is completed.

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

  • You set param = 1 and sent the first ajax request
  • You set param = 2 and send a second ajax request
  • The first call will be completed. The callback for this call is being processed. Your param variable is now 2
  • The second call will be completed. The callback for this call is being processed. Your param variable is still 2

The solution is to have different variables for each call or to increase param and send a second ajax call inside the callback function of the first.

+1
source

Source: https://habr.com/ru/post/1310550/


All Articles