Good day. There is a function that loads data using Ajax request to the database data by user Id

function getDialogToId(idVk){ var pageRez='0'; $.ajax({ url: 'http://site.ru/ajax/ids.php', type: 'POST', data: 'func=getDialogToId' + '&idVk=' + idVk, dataType: 'json', }).done(function(rez) { pageRez = rez.page; }).fail(function() { alert('ОШИБКА, что-то не так'); }); return pageRez; } 

But the problem is that as soon as I call it in a loop, the variables come undefined, tell me what's the matter? Why doesn't the function wait for the result that should come in the Ajax request, but immediately returns a non-defined variable? and how can this be fixed? Thank.

Here is the calling code:

 getDialogToId('5093649'); 

Reported as a duplicate by the participants Duck Learns to Hide , Crantisz , Dmitriy Simushev , Bald , vp_arth 7 Mar '17 at 9:34 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • How do you call in a loop, which variable is undefined ? Add code to the question - ThisMan
  • one
    In general, take a look at promiseAll - ThisMan

1 answer 1

Ajax runs asynchronously by default, i.e. your code continues to execute, returns undefined, and only much later completes the execution of an ajax request with assignment of the result.

The easiest (though not the best way) - add

 async: false, 

in ajax request. The browser will warn you, but the code will work as you expect.

  • one
    though not the best == for recommending such methods in a decent society they beat the cap) - Duck Learns to Take Cover
  • Thank you, but I agree with the previous commentator, this option does not fit. - Maxim147
  • @ DUCK LEARNING on the cap can be obtained in response. A decent society is called a society where they do not speak maliciously, but give the best answers, explaining (not to me, I already know everything without you) why the proposed answer is bad and what are its pitfalls. Given the level of user training (on the issue it is clear that he didn’t guess at all about asynchrony), I proposed the simplest solution. - KAGG Design
  • @ Maksim147 it would be interesting to hear why. That's why - absolutely) - KAGG Design
  • @KAGGDesign, the simplest and generally harmful solution. - Duck Learns to Take Cover