Reputation: 13712
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";
});
Upvotes: 6
Views: 13405
Reputation: 22820
You can't execute a function while another is being executed in JS, being it mono-threaded: you can do stuff before and after though - are you looking for a way to setup a message / spinner to be shown while waiting? Check beforeSend option 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";
});
Upvotes: 1
Reputation: 4024
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
}
// ......
});
Upvotes: 3
Reputation: 935
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.
Upvotes: 15