jQuery: sending an email with AJAX

Sending emails with AJAX is a common feature in a Web 2.0 application. jQuery can actually ease this process through its $.ajax() wrapper. To accomplish this task, you basically need a server side script for processing data and sending the email. For example, if you use PHP, you need something like this:

header('Content-Type: text/plain');

$subject = $_POST['subject'];
$message = $_POST['message'];
$email_from = 'you@site.com';
$to = $_POST['to'];
$headers = "From: John" . " " .  "Doe" . " " . "<". $email_from . ">" . "\r\n";

$recipient = "<" . $to . ">";

if(mail($recipient, $subject, $message, $headers)) {
        echo '<p class="success">Email sent successfully.</p>';
 } else {
        echo  '<p class="error">Problem with sending email.</p>';

Adding jQuery is quite easy at this point:

function sendEmail() {

    $('#email-form').submit(function() {
    var subject = $('#email-form #subject').val();
 var message = $('#email-form #message').val();
 var to = $('#email-form #to').val();
 var data = 'to='+to+'&subject='+subject+'&message='+message;
     type: 'POST',
     url: 'http://yoursite.com/mail.php',
     data: data,
     success: function(html) {
 return false;


Note two things in our example:

  1. I've used return false to prevent the form from performing its default action (that is, opening the URL specified in the action attribute)
  2. I've served the response as text/plain, because it's considerably faster than other types of responses.

Leave a Reply

Note: Only a member of this blog may post a comment.