Send local variables to Ajax

0

I have a cycle for and inside a call ajax . In success I use a variable that is "processed" with the cycle and is different for each call in the ajax. The problem is that the success does not seem to be taking the corresponding values for this variable.

Example:

 for(var i = 0; i < longitud; i++) {
      $.ajax({
         url: url,
         data: data,
         type: 'POST',
         success: function(data) {
              if(data.status){
                   // En este punto i es undefined
                   $("#div"+i).html("Hi");
              }
         }
      });
 }
    
asked by Islam Linarez 22.12.2017 в 00:27
source

2 answers

3

Friend the ajax requests are asynchronous, which means you do not know when the response lasts.

That's why the for if you execute the requests but the variable i gets it back after the time it took to go and make the request so i is worth 10 because the time of the for is much faster than that of each request within the.

I hope you help greetings.

  

NOTE : A test API was used to make the query.

Example

var root = 'https://jsonplaceholder.typicode.com';

for(var i = 0; i < 10; i++) {

$.ajax({
  url: root + '/posts/1',
  method: 'GET'
}).then(function(data) {
  console.log(i);
});

 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Solution

If you want you can do a cursive function that only runs when you return the ajax would be like your own for

  

The idea is to execute the ajax and that when returning, call the same function but with the condition variable with a number until it is fulfilled and Ajax is not executed anymore.

Functional example

var root = 'https://jsonplaceholder.typicode.com';

 var numero = 0
 function miFor(numero){
  if(numero<10){
  $.ajax({
  url: root + '/posts/1',
  method: 'GET'
   }).then(function(data) {
   console.log(numero);
   numero++
   miFor(numero)
 });
  }
 }
 miFor(0)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
answered by 22.12.2017 / 00:57
source
0

You must make your ajax requests synchronous. jQuery.ajax() has one of its parameters intended for that purpose async which by default is true .

var root = 'https://jsonplaceholder.typicode.com';

for(var i = 0; i < 10; i++) {

    $.ajax({
        url: root + '/posts/' + i,
        method: 'GET',
        async:false
    }).then(function(data) {
        console.log(data);
    });

 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
answered by 22.12.2017 в 15:25