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";
});

Answers:

Answer

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.

Answer

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
   }
   // ......
 });
Answer

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";
});

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.