Running a function before async ajax request Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Running a function before async ajax request without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I’m trying to run a function before async ajax request. However function is running after async request gets the respond.

Is there any way to solve this issue?

block();

ajaxRequest= $.ajax({
    url: siteURL+'includes/ajax/action.php',
    type: "POST",
    async: false,
    data: {productID : productID},
    dataType: "json"
});
ajaxRequest.done(function(data) {
            block(true);
            if (data === false) {
                alerts('error title','error info here', 'error', 200);
                return false;
            }
});
ajaxRequest.fail(function(jqXHR, textStatus) {block(true); alerts('error title','error info','error');});
confirm();

I run more functions after these codes. However as I stated before, block(); function is waiting till async ajax request is getting response.

If I don’t run asynchronous, then I get block() and confirm() functions running at the same time so return false; losing all the meaning.

P.S. I run these codes when a form is submitted so if async request is failed I don’t want it to run any other code after it. However when it is asynchronously running block() is waiting till response is returned.

Answer

Your problem is async:false. Your request is NOT an async request, it is a sync request. It blocks javascript code and browser rendering from happening while the request is being processed. With your current setup, there should be no harm in removing async: false, thus making it async.

block();

ajaxRequest= $.ajax({
    url: siteURL+'includes/ajax/action.php',
    type: "POST",
    data: {productID : productID},
    dataType: "json"
});
ajaxRequest.done(function(data) {
            block(true);
            if (data === false) {
                alerts('error title','error info here', 'error', 200);
                return false;
            }
});
ajaxRequest.fail(function(jqXHR, textStatus) {block(true); alerts('error title','error info','error');});
ajaxRequest.always(confirm);
We are here to answer your question about Running a function before async ajax request - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji