Skip to content

January 2, 2010

5

Simple Ajax Form Tutorial

Submitting an Ajax form using Dojo is very straightforward and simple. The main goal here is to simply send the values of a form to a backend script (whatever your preference, e.g. PHP or Python), without ever leaving the page. The page should also show a response to the user confirming that their request was sent successfully.

For starters, we need a simple HTML form that we are going to send. Construct this as you normally would with an id, action, and method values. In my example, I’ve created a basic contact form:

<h1>Contact Form</h1>
 
<form id="contact" action="contactFormAction.php" method="POST">
  <dl>
    <dt><label for="txtFirstName">First Name:</label></dt>
    <dd><input id="txtFirstName" name="firstName" type="text" /></dd>
 
    <dt><label for="txtLastName">Last Name:</label></dt>
    <dd><input id="txtLastName" name="lastName" type="text" /></dd>
 
    <dt><label for="txtEmail">Email Address:</label></dt>
    <dd><input id="txtEmail" name="email" type="text" /></dd>
 
    <dt><label for="txtComments">Comments / Suggestions</label></dt>
    <dd><textarea id="txtComments" name="comments"></textarea></dd>
  </dl>
  <input id="submit" type="submit" value="Submit Form">
</form>

As you can see, I have my contact form posting to a PHP script called contactFormAction.php. This is a very basic script that doesn’t actually email in our demo. It simply will read one of the values that is posted from the form, firstName, and display that along with a message encoded in a JSON string.

The contents of my contactFormAction.php file is:

<?php
  // Logic to send an email would go here
  // for now we are just going to send back a simple
  // JSON response to show a successful submission
  echo '{"success":"true","message":"Message sent successfully to ' . $_POST["firstName"] . '."}';
?>

Note, that in order for something to be considered as a proper JSON string, it needs to have all the properties and values in quotes.

At this point, if you were to setup these two pages and your webserver and submitted the form, everything would work as expected. The only difference is that when you posted the form, the browser would direct you to the PHP script to show it’s output. The whole idea with this exercise however is to submit this form without leaving the page and notifying the user that it was successful. This is very simple with Dojo’s xhrPost() function.

We need to first pull the Dojo toolkit library into our page by simply putting the following in the HEAD of our HTML page:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/dojo/1.4/dojo/dojo.xd.js"></script>

Once we have that included we can write the following JavaScript between a script block in our HEAD as well:

dojo.addOnLoad(function(event){
  dojo.connect(dojo.byId('submit'), 'onclick', function(event){
    dojo.stopEvent(event);
    dojo.xhrPost({
      form: 'contact',
      handleAs: 'json',
      load: function(data) {
        console.log(data);
        var success = data.success;
        var msg = data.message;
        if(success) {
          dojo.byId('responseMsg').innerHTML = msg;
        }
      },
      error: function(error) {
        console.log(error);
      }
    }) // xhrPost()
  }); // connect()
}); // addOnLoad()

This series of anonymous functions first creates a listener for when the page has completed loading (addOnLoad()), then sets up an event listener to listen for the onclick event from the submit button (dojo.connect()). Inside that event listener function we first stop the click event from proceeding with it’s default actions (i.e. submitting the form in a traditional manner), and we proceed with the xhrPost() function.

Dojo’s xhrPost() allows you to simply provide the id of a form element for it to determine where to post the form’s contents to. This is convenient because if you want the form to be able to be submitted even if the user didn’t have JavaScript support in their browser (such as some mobile devices), they still could. If they do have JavaScript support, then the xhrPost() function will send the Ajax request to the URL in the action attribute of the form. The handleAs property tells xhrPost what type of data will be returned from the script you are posting to. In my case, I created the PHP script to return a JSON string. Upon successful posting to that script, it will return a JSON string, and xhrPost will parse the string and turn it into a JavaScript object automatically and send it to our load function. The load function simply receives a single attribute which I called data. This is what our response will be sent back in. In my load function I first log to the Firebug console the value of data, then I determine if success was true and if it is I display the included message to the element with the id of “responseMsg”. I added this element inside a fieldset block below the form:

<fieldset>
  <legend>Response from server</legend>
  <p id="responseMsg"></p>
</fieldset>

That’s the basis of it, very easy and straightforward. Check out an online demo of this simple Ajax contact form.

Read more from Tutorials
5 Comments Post a comment
  1. Nathan Waters
    Jul 29 2010

    Hmm, for some reason when I throw that code into the all my navigation is killed across the site. i.e. cannot click any link hrefs

  2. Kyle Hayes
    Jul 30 2010

    @Nathan, that’s odd since the click handler is only used for a specific element with the id=”submit”. Do you have some sample code?

  3. Nathan Waters
    Aug 16 2010

    I sorted it out, it was something stupid… forget what it was :)

    My issue now is I’ve been customizing this code for an image generator (i.e. people enter the text into a textbox, hit “Make” and it instantly generates the image).

    I’ve got that working, but I’m now trying to add a Facebook share button that has it’s share URL dynamically updated as the user creates the new image.

    However, from searching I’ve found that innerHTML destroys any other javascript events.

    e.g. code inside contactFormAction.php:

    echo ‘{“success”:”true”,”message”:”Share“}’;

    I’m a fair noob at this stuff, is there a quick workaround to have the button work after the innerHTML replace?

    Cheers

  4. Nathan Waters
    Aug 16 2010

    Woops, code executed… here it is again:

    echo '{"success":"true","messagetext":"Share"}';
  5. Nathan Waters
    Aug 16 2010

    Gah lol… well yeah you get the idea. I’m trying to include the Facebook button share code, and passing a variable to change the share URL. Executes fine, but the javascript elements involved in the FB button don’t work after the fact.

Share your thoughts, post a comment.

(required)
(required)

Note: HTML is allowed. Your email address will never be published.

Subscribe to comments