Hello. At the beginning of the js script, I need to send an ajax request, retrieve data from it, and only then continue with the script. Now I have the following code: var user_data = getdata (count); The getdata method sends a get request to the script. The problem is that when the user_data variable is needed, it is still empty, because we did not receive a response from the server. How to act in this case? getdata method returns an array from JSON.parse

  • If the user_data variable is needed before the response is received, then nothing can be done. - Vladimir Gamalyan
  • You can use callback functions. I could be wrong if I did not understand the question. false will solve the problem xhr.open('POST', url, false); . The script will not go further until the request is fulfilled - Mr. Black
  • Redo the script so that it is executed in a callback when the ajax request is completed. Synchronous requests have long been canceled everywhere or are no longer working. You can specify async = false only in Worker-e (a separate thread), which will be almost equivalent to launching a normal asynchronous request in the main thread. - Sergey

2 answers 2

You can use $.when and its promise https://api.jquery.com/jquery.when/

If only one deferred object is passed to $.when() , it will simply return its promise version. In addition to deferred-objects in $.when() you can specify any other js-objects. jQuery will always determine their state as successful.

Example:

 $.when( $.ajax("test.aspx") ).then(function(data, textStatus, jqXHR){ alert( jqXHR.status ); // выводит 200 }); 

Accordingly, you shove your request in when , and after its execution you finish your dirty work:

 $.when( $.ajax( "/page1.php" ) ).done(function( data ) { // делаете что-то что вам нужно сделать // var response = data[ 0 ] + data[ 1 ]; // alert(response); // ... // ... }); 
  • ajax returns promise, no need when use - Grundy
  • one
    @Grundy yes, probably when it makes sense when you need to run asynchronously several at the same time - Alexey Shimansky

Solved the problem by concluding everything you need when in $.get("имя скрипта" , { user_number: count} ).done(function( data ) {