Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery continue another ajax function after the first ajax function call is fully complete

Tags:

jquery

ajax

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:'',
      });
});
like image 505
vzhen Avatar asked Sep 20 '12 16:09

vzhen


People also ask

How do I make jQuery wait for an Ajax call to finish before it returns?

If you don't want the $. ajax() function to return immediately, set the async option to false : $(". my_link").

How do I return data after Ajax call success?

You can store your promise, you can pass it around, you can use it as an argument in function calls and you can return it from functions, but when you finally want to use your data that is returned by the AJAX call, you have to do it like this: promise. success(function (data) { alert(data); });

How do you check if all AJAX calls are completed?

jQuery ajaxStop() Method The ajaxStop() method specifies a function to run when ALL AJAX requests have completed. When an AJAX request completes, jQuery checks if there are any more AJAX requests. The function specified with the ajaxStop() method will run if no other requests are pending.


2 Answers

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});
    }
like image 179
Explosion Pills Avatar answered Nov 02 '22 19:11

Explosion Pills


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.

like image 29
Timothy Groote Avatar answered Nov 02 '22 19:11

Timothy Groote