Jquery execute function when loading ajax response

How can I execute a function that will work while the client is waiting for a server response? Here is my code. I looked up and found the .load () function, but how does this 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"; }); 
+4
source share
3 answers

The very next line of code that you write after you call $ .ajax () when the browser expects a response.

So:

 $.ajax(); yourAwesomeFN(); 

XhttpRequests are asynchronous. No extra work required.

+11
source

You looked at the "beforeSend" parameter .

 $.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 } // ...... }); 
+2
source

You cannot execute a function while the other executes in JS, being mono-threaded: you can do things before and after , though - are you looking for a way to set a message / counter to be displayed while waiting? Check beforeSend in $.ajax() call:

 $.ajax({ type: "POST", url: "mail.php", data: {name: name.val(), email: email.val(), phone: phone.val(), subject: subject.val(), message: message.val()} beforeSend : function(){ // do your stuff here } }).done(function(){ alert("Your message was sent. We will be in contact with you shortly."); window.location="index.html"; }); 
+1
source

All Articles