Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery execute function while ajax response is loading

How can I execute a function that will run while the client is waiting for the server response? Here is my code. I looked up and found a .load() function, but how does that fit into this? Any help would be great! Thanks

$.ajax({
    type: "POST",
    url: "mail.php",
    data: {name: name.val(), email: email.val(), phone: phone.val(), subject: subject.val(), message: message.val()}
    }).done(function(){
        alert("Your message was sent. We will be in contact with you shortly.");
        window.location="index.html";
});
like image 235
eatonphil Avatar asked Aug 25 '12 20:08

eatonphil


People also ask

How can call jQuery function after AJAX success?

The ajaxComplete() method specifies a function to be run when an AJAX request completes. Note: As of jQuery version 1.8, this method should only be attached to document. Unlike ajaxSuccess(), functions specified with the ajaxComplete() method will run when the request is completed, even it is not successful.

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 does .post work in jQuery?

jQuery $.post() Method The $.post() method requests data from the server using an HTTP POST request. Syntax: $.post(URL,data,callback); The required URL parameter specifies the URL you wish to request.


2 Answers

The very next line of code you write after You call $.ajax() will run while the browser is waiting for a response.

So:

$.ajax();
yourAwesomeFN();

XhttpRequests are asynchronous. No extra work required.

like image 200
Macdiesel Avatar answered Sep 27 '22 23:09

Macdiesel


Have you looked in the "beforeSend" param.

$.ajax({
type: "POST",
    url: "mail.php",
    data: {name: name.val(), email: email.val(), phone: phone.val(), subject: subject.val(), message: message.val()},

   beforeSend: function(){
     // Handle the beforeSend event
   },
   complete: function(){
     // Handle the complete event
   }
   // ......
 });
like image 28
Amin Eshaq Avatar answered Sep 27 '22 22:09

Amin Eshaq