Execute a js function only after the ajax request fully compleated

15,486

Solution 1

You should use $.ajaxComplete();

$(document).ajaxComplete(function() {
  alert("compete");
});

this would be triggered after every Ajax call you make on the page

otherwise you use ajax() and set the complete property

$.ajax({
  url: "myurl",
  complete: function(){
              alert("complete");
            }
  //set all the other options as usual

Solution 2

You can use the callback to any of the jQuery AJAX methods to delay execution of another function until after the request is complete.

Example:

   $.post('/some/url', somedata, function() {
        // put the code you want to execute on completion here
   });

For more complicated scenarios, use the actual ajax method which gives you hooks for success, completion, error and other events. Typically, you'd only need success and error.

   $.ajax( '/some/url', {
        data: somedata,
        type: 'post',
        success: function(result) {
           // success code execution here
        },
        error: function(xhr,status,error) {
           // error code here
        },
        complete: function(xhr,status) {
           // completion code here
        }
   });

Solution 3

If you want to do this for a particular call, then the complete function is likely what you need. If you want this to be global, for all ajax calls, then Nicola's answer should be what you need.

Here's the jQuery documentation for Ajax calls.

Share:
15,486
Shibin V.M
Author by

Shibin V.M

Updated on June 18, 2022

Comments

  • Shibin V.M
    Shibin V.M almost 2 years

    I want to execute a js function only after the jquery ajax call fully completed.(After Success and Error Events completed). ie after ajax call puts incoming data to an element.

    How to achive this.