How to Send PHP Email using Jquery AJAX without Page, Form Refresh or Reload

In my previous posts I have discussed the power of Jquery, using it for AJAX functionality and sending a PHP email with proper headers.

Case Study

Today we will combine all the three top graded functionality to form one identity. In the world of Web 2.0 developers get a request very often that a user fills up a website form and an email should be fired without refreshing of the page and also a “Thanks” message should be displayed on the same page.

Now what are the steps to do that?

1. Download a Jquery javascript library.

2. Validate the form with javascript.

3. On submit of the form  call Jquery function $(“#frm”).submit(function{})

Note. frm is the id of the form and Jquery will always deal with the HTML elements ID.

4. Write a Jquery code to interact with the PHP script to fire an email.

5. While the PHP script is executed show a “Please Wait…” message to the user. You can also a show a loading image. Something like-

$(“#display_thanks”).html(“<img src=”loader.gif”>”);

You can replace the above code in my script against the “Please wait…” message.

6. Get a response from the PHP script and show a thanks message to the user.

7. You are done.

Click here to view this in action

Lets see how are JQuery snippet look like-

//Call the Jquery functions only when the Page elements are fully downloaded. Here we do not take of  Images.
$(document).ready(function(){

$("#frm").submit(function(){

//Form Validation function is called
if(!checkMyForm())
{
return false;
}

//Display Please wait message. You can also show loader image
$("#disp_thanks").html("Please wait...");
$("#disp_thanks").show();
//POST values through JQUERY AJAX functions

$.post("get_query.php",{contact_name:$("#contact_name").val(), email:$("#email").val(), phone:$("#phone").val(), query:$("#query").val() } , function(data)
{

//if you get a response from the PHP file "get_query.php" above that the mail has been fired then show thanks message-
if(data)
{
// show div in effect
$("#disp_thanks").html("Thanks for your enquiry!");
}
});

});

});

Let me know if you have any queries.

So Happy Jquering and Ajaxing with PHP emailing… 🙂

Both comments and pings are currently closed.

One Response to “How to Send PHP Email using Jquery AJAX without Page, Form Refresh or Reload”

  1. Joy Schnabl says:

    Useful info and excellent design you got right here! I want to thank you for sharing your thoughts and putting the time into the stuff you publish! Nice work!