19

I have 2 ajax call in 2 difference functions. I want to use .click to call these 2 functions . The func1 is inserting data in to database, then func2 is to retrieve the data so my question is how to wait until the func1 fully complete then it only execute the func2.

I tried .delay(), it works but i think this is a stupid solution.

  $("#updateLocation").click(function(e){
      e.preventdefault;
        func1();
        func2();
      });
      return false;
    });

    function func1(){
      $.ajax({
        url:'',
      });
});

    function func2(){
      $.ajax({
        url:'',
      });
});
vzhen
  • 11,137
  • 13
  • 56
  • 87

7 Answers7

33

Three ways:

Call func2 on success of func1:

    function func1() {
       $.ajax({ ... }).done(func2);
    }

Use Deferred API to call func2 when funky completes:

    e.preventDefault();
    $.when(func1).then(func2);

Make func1 synchronous (not recommended):

    function func1() {
       $.ajax({url: '', async: false});
    }
David Hoelzer
  • 15,862
  • 4
  • 48
  • 67
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • a slight variation you have 2 independent ajax calls that you want to just async but then you want to start a 3rd when both have completed which should be `$.when(func1,func2).then(func3);` – MikeT Nov 10 '17 at 14:12
  • 1
    Can also be accomplished with a newer JS syntax using async / await function (may require Babel, though to work in browsers): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function Just a note here since the question was specifically about AJAX. – wondersz1 Feb 19 '18 at 16:17
7

Since Ajax calls are asynchronous, the application will not 'pause' until an ajax call is complete, and simply start the next call immediately.

JQuery offers a handler that is called when the call is successful, and another one if an error occurs during the call.

$.ajax({
  url: 'ajax/test.html',
  success: function(data) {
    $('.result').html(data);
    alert('Load was performed.');
  },
  error :function(jqXHR, textStatus, errorThrown)
  {
     alert("something went wrong");
  }
});

You will want to call your second AJAX function from the success handler.

Timothy Groote
  • 8,614
  • 26
  • 52
3

Move func2 inside func1->ajax->succes callback

$("#updateLocation").click(function(e) {
    e.preventdefault;
    func1();
    //func2();
});
return false;
});

function func1() {
    $.ajax({
        url: '',
        success: function() { /* other stuff */
            func2();
        }
    });
});

function func2() {
    $.ajax({
        url: '',
    });
});
Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134
2

You can set the option "async" to false (for the first ajax call).

This means that function 2 will be called after function 1 has received a response, i.e. finished it's execution.

    function func1(){
      $.ajax({
        url:'',
        async: false
      });
});
Tool
  • 12,126
  • 15
  • 70
  • 120
  • Keep in mind that doing this will pause your entire script and cause it to 'hang' until the (now synchronous) operation is complete! – Timothy Groote Sep 20 '12 at 17:01
  • 1
    Just a note here: it's been a long time since this reply and AJAX async: false option is now deprecated. – wondersz1 Feb 19 '18 at 16:23
2

Call fun2 in success of func1

function func1(){
  $.ajax({
    url:'',

    success:function(){
         func2();
    }  
  })
Adil
  • 146,340
  • 25
  • 209
  • 204
0

Simply use the ajaxComplete function, it has 3 optional parameters and in the settings, parameter ajax action URL or type data we received so on the basis of these data, we will set a condition.

$( document ).ajaxComplete(function( event, xhr, settings ) {
    if( settings.url != '/wp-admin/admin-ajax.php?action=get_location_form' && settings.type === 'POST') {
       get_location_form();      // replace function with your custom logic here
    }
});
-1

you could also pass your function as a parameter like this:

var secondFunc = function (func) {

    //Do ajax req or smt
    func("answer", "params");

};
var firstFunc = function() {

    secondFunc(
        function (answerFromFunc2, paramsFromfunc2) {

            var a = answerFromFunc2;
            var b = paramsFromfunc2;

        }
    );

    //Do smt after the function request to the server is done
    var doSmt = "another func or variable";

};
firstFunc();
superzebb
  • 19
  • 2