Skip to content

January 2, 2010

21

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
21 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.

  6. Al
    Oct 10 2010

    here we go again, another script that doesnt work because its author does not have any interest in people actually learning but to make a name of themselves, be popular etc. The php script is missing so I have wasted my time again. I have spent 36 hours searching for a correct, most simple, no validations, no css Ajax form, nothing, there is none on the internet like that which works.

  7. Kyle Hayes
    Oct 10 2010

    Hey @Al, I’m not exactly sure why you are saying the PHP script is missing—I’ve put the source of the PHP code right into the the text of the article above. What is it that you think is missing? Also, is there something that you are looking for in particular? This is a simple Ajax Form Tutorial, if you would like something more advanced let me know and perhaps I can put something together.

    It’s not appropriate going around to people’s blogs leaving rude comments that don’t pertain to the content. In addition, if the author, me, was in it to make a name for myself and be popular, I wouldn’t be writing a tech blog on Dojo.

  8. Dec 30 2010

    Hey Kyle,
    I could only get this to work if I added url: ‘contactFormAction.php’, to the xhrPost. Not sure why that is, but it was attempting to xhr to null before that.
    -cbarrett1

  9. Charles
    Feb 12 2011

    is it only me but the example isnt working? I copy paste it with the php file as well, run it, but te response doesn’t modify the message, in firebug it shows that the response is the whole php file..

  10. Kyle Hayes
    Feb 12 2011

    Hey Charles,
    What server setup are you using to serve the PHP?

  11. Charles
    Feb 12 2011

    It works!!!! sorry Kyle!!! I apologize… somehow the setup for php was wrong.. (I messed it up!)

  12. Kyle Hayes
    Feb 12 2011

    Don’t sweat it! I’m just glad you got it to work.

  13. Chris
    Mar 17 2011

    Hey, thanks for this simple form. Unfortunately I have the same issue Nathan had. My navigation has also been killed by it for some reason.
    Any idea what this could be?
    Thanks

  14. Kyle Hayes
    Mar 18 2011

    Hey Chris, does the form post not work either? Also, can you clarify about the navigation not working?

  15. Chris
    Mar 18 2011

    Yeah the form works great. The script itself works very well. As sson as I added the Javascript the links stopped working. Basically you can hover over links as normal and the url is displayed in the browser so they are still linked, but when you click them nothing happens. They do not link anywhere. Really not sure what it is. Any help would be greatly appreciated.
    Thanks

  16. Chris
    Mar 18 2011

    Using the Error Console in Firefox, when a link is clicked it gives the message:
    “Error: form is null
    Source File: http://ajax.googleapis.com/ajax/libs/dojo/1.4/dojo/dojo.xd.js
    Line: 16″
    It highlights the entire dojo function as being the problem.
    Thanks

  17. Kyle Hayes
    Mar 18 2011

    Ah ok, interesting. It seems that it’s not able to find the form by that id. Assuming your form has the id of “contact”, try replacing form: “contact” with form: dojo.byId(“contact”)

    See if that makes a difference. Otherwise, drop the form attribute altogether and add a url attribute instead that you want the request to post to. This would likely be the URL that you were using for the “action” attribute on the form.

  18. Ty
    Oct 6 2011

    Hi,

    Great little article, I have come across a problem though and that is that my dojo form when being filled out is constantly posting that data to the target page so as soon as I tab from username to password it posts the username. Rather an odd behavior. It also disables the submit and reset button so I cannot submit the entire form…. Thanks

    return confirm(‘Press OK to reset User values’);

    if (this.validate()) {
    return confirm(‘Form is valid, press OK to submit’);
    } else {
    alert(‘Form contains invalid data. Please correct first’);
    return false;
    }
    return true;

  19. Kyle Hayes
    Oct 6 2011

    Hey bud, if you can, it would be great to see a bit more code. Can you replicate the issue on jsfiddle.net ?

  20. Ty
    Oct 6 2011

    Hi mate, sorry, it truncated a bit there. JSfiddle seems to have weird layout output, probably something I did in there as test on my PC layout fine.

    Your code is as above except form name changed to match below.

    return confirm(‘Press OK to reset User values’);

    if (this.validate()) {
    return confirm(‘Form is valid, press OK to submit’);
    } else {
    alert(‘Form contains invalid data. Please correct first’);
    return false;
    }
    return true;

    User Name:

    Submit

    Reset

    Response from server

  21. Ty
    Oct 6 2011

    Darn, it truncated again, there must be a bug or something preventing that code being posted.

    Basically it is a Dojo Ajax form with Ajax validation which works fine, and your code is as above just with form name changed.

    It is definitely posting ok as it comes back with the right message, just if I can stop it submitting each time I change fields that would be great! :)

Share your thoughts, post a comment.

(required)
(required)

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

Subscribe to comments