简体   繁体   中英

Running ajax request in javascript synchronously?

I am having this problem with my code. I have a function performing AJAX call and bringing up the interface and that AJAX is separated in a different function. I am calling it in somewhere and some code follows it. Here is an example :

function doAjaxStuff(){
//do something
}

function anotherFunction(){
doAjaxStuff();
//proceed with further code
}

(The function anotherFunction is getting called from $(document).ready )

As the further code is completely dependent upon the things I'm loading, like I'm trying to accessing an element and it hasn't loaded yet which gives me null value and nothing works. So if i could just wait till the function that i called in anotherFunction gets executed completely then it would be easier for me to deal with it. I've seen promises if I'm not wrong helps in making code synchronous (Not able to understand how to implement that). Help me out!

You can pass a callback function as argument to doAjaxStuff and call it when your ajax request is done.

function doAjaxStuff(callback) {
    $.ajax({
        success: function(data) {
            // do some stuff with data
            callback(data);
        }
    });
}

function anotherFunction() {
    doAjaxStuff(function(data) {
        alert(data);
    })
}

In JavaScript, functions are also objects, which means they can be passed as argument to another function as well as you can do with any other value. So in this case we have a parameter called callback in the function doAjaxStuff . When the ajax request is complete, we can call this function that was passed as argument.

Another way is to use deferred objects

function doAjaxStuff(){
  return $.ajax(...);
}


function anotherFunction() {
    $.when(doAjaxStuff()).then(function(){
       // other code to run after ajax call
    });
}

try something like this

      $.ajax({
        url:"demo_test.txt",
        async:false,
        success:function(result){
        }
     });

all requests are sent asynchronously (ie this is set to true by default). If you need synchronous requests, set this option to false

REFERENCE

http://api.jquery.com/jquery.ajax/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM