Using jQuery to Send Email with Web Services

by Max Slabyak

Note: to see the code for the .NET web service to be used with jQuery code below, see new post here:
How To Build a JSON Web Service to Send Mail in ASP.Net



Just to make sure we are all up to speed, a quick concept in extreme layman’s terms

- jQuery is a front-end thing, meaning it gets your browser to do stuff, like move stuff around and change stuff after it’s already been loaded from the server.

- Sending email is a back-end thing, meaning it requires talking to the server to send stuff.

Now that we are all up to speed, including my 5-month-old daughter, I think it’s clear that jQuery alone can’t do this, at least not without help.  How does jQuery get help from the server? It uses an AJAX Post method to talk to a server, in our case, a web service, to send something and then get something back in return, like a result, which could be ignored by not specifying it in the AJAX Post call.

For this exercise, because I prefer .NET to PHP, I will be using a very simple .NET web service to send out the email, but this task can be accomplished by any server that accepts HTTP Post commands, like a CGI script.
Let’s review the steps that we will take to accomplish this task:

  1. Validate form data
  2. Send data to web service
  3. Interpret & display results from web service

Validating Form Data

jQuery has a great validation plugin that is very easy to use out of the box – jQuery Validate.  To demonstrate just how simple it is, we can validate an email form by using a css class “required” and a simple $(“emailform”).validate() in the $(document).ready function.  The other cool thing about this plugin is you won’t have to write your own Google for a regular expression on validating email addresses.  Check out the code example below that I borrowed from the jQuery page for this plugin (http://docs.jquery.com/Plugins/Validation)


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
<style type="text/css">
* { font-family: Verdana; font-size: 96%; }
label { width: 10em; float: left; }
label.error { float: none; color: red; padding-left: .5em; vertical-align: top; }
p { clear: both; }
.submit { margin-left: 12em; }
em { font-weight: bold; padding-right: 1em; vertical-align: top; }
</style>
  <script>
  $(document).ready(function(){
    $("#commentForm").validate();
  });
  </script>

</head>
<body>

 <form class="cmxform" id="commentForm" method="get" action="">
 <fieldset>
   <legend>A simple comment form with submit validation and default messages</legend>
   <p>
     <label for="cname">Name</label>
     <em>*</em><input id="cname" name="name" size="25" class="required" minlength="2" />
   </p>
   <p>
     <label for="cemail">E-Mail</label>
     <em>*</em><input id="cemail" name="email" size="25"  class="required email" />
   </p>
   <p>
     <label for="curl">URL</label>
     <em>  </em><input id="curl" name="url" size="25"  class="url" value="" />
   </p>
   <p>
     <label for="ccomment">Your comment</label>
     <em>*</em><textarea id="ccomment" name="comment" cols="22"  class="required"></textarea>
   </p>
   <p>
     <input class="submit" type="submit" value="Submit"/>
   </p>
 </fieldset>
 </form>
</body>
</html>

Send Data To Web Service

This step is a bit more tricky, at least if you want it to be cross-browser compatible. The jQuery method is $.ajax, with type POST that looks something like the code below:


$.ajax({
  type: 'POST',
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

That’s the basic skeleton of an AJAX POST, but we will need to modify it to look like this:


 $.ajax({
  type: "POST",
  url: "/services/Mail.asmx/SendMail",
  cache: false,
  contentType: "application/json; charset=utf-8",
  data: "{ 'body':'"  + messageBody + "'," +
      "'to': '" + msgTo + "'," +
      "'from': '" + msgFrom + "'," +
      "'subject': " + msgSubject + "'" +
      "}",
  dataType: "json",
  complete: function (transport) { if (transport.status == 200) $("#formcontainer").html("Success"); else alert("Please try again later"); }
        });

So here is what’s happening, and BTW – the above code uses some different variable names than the validation code above, but I am sure you can deduce that msgSubject is a variable that has the value from a textbox containing the subject :

  • type – POST (becasuse we are doing an HTTP POST)
  • url – since we are using ASP.NET Web services, it follows the servicepage.asmx/webmethodname format
  • cache – false (we want to make sure to send fresh form results every time)
  • contentType – this is where we set up our communication type.  We can do SOAP, or JSON, the latter being a lot more lightweight.
  • data – this is where your parameters get passed in.  Since we are using JSON, we will want to format the parameters with the correct string delimiters -
    { ‘variable1′:’value1′,’variable2′,’value2′}
  • dataType – same as contentType, just a different way of specifying the format
  • complete - we can listen for success, error, and complete.

Interpret & Display Results

The reason you don’t see the success or error events up above is because, while cross-browser testing, even when the sending of the mail was successful, it was firing both success and error events.   The way to guarantee correct execution is to poll for the HTTP status after the web service executes. That’s why we are checking for transport.status being equal to 200, which is a successful HTTP code.

To display different results, we just need to inject the desired HTML formatted results into the div or another HTML container that houses your results by using the $(“#formcontainer”).html(“Your result”) method.

Other Notes

You will need to get your submit button to fire off the AJAX POST call.  You can give the button an id or class and fire up the onclick event using jQuery like  $(“imgsubmitbutton”).click(function {}); – just make sure to return false as the last line of the function, otherwise the page will refresh.

Demo

Of course, no post on jQuery would be complete without a demo, so I’ve put together on jsFiddle here - http://jsfiddle.net/aM7PR/55 .  Couple of notes about it:

  • With jsFiddle, you can make mock JSON calls, so it will always come back successful.
  • If this is a “Contact Us” form, you don’t really want to have both a From and a To field, because you will be a spam magnet, so you can hard code the To email address in your web service.

Share

3 thoughts on “Using jQuery to Send Email with Web Services

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>