AJAX has been the new hotness in web development and the recent web 2.0 craze. By carefully utilizing AJAX, web designers and developers can create a seamless and smooth user experience. Users can continue interacting with a page without breaking the experience with page reloads or redirects.

Lately, I have been asked by many of my web designer friends how to submit a form via AJAX. With jQuery, the process is incredibly simple.

We will use AJAX to submit a very simplified registration form to another PHP page, ajax-register.php. The form will ask the user for their name, their email, and a password. This prevents us from doing any extra logic to check matching passwords.

To download the source code click here. You could also try out a demonstration here.

Update: Modified the code so the form will degrade gracefully if JS is turned off. Special thanks to Erol for pointing this out!

Before we begin

Troubleshooting AJAX can be a pretty difficult process at times. If you don’t have it already, I highly suggest you download Firefox and download the Firebug addon. It makes troubleshooting AJAX and frontend code a breeze.

Include jQuery in your page

Add these to your headers and let Google serve up jQuery for you. No point in using up extra bandwith when Google can serve up jQuery much faster.


Create the form

The first thing you need to do is create your form in HTML. For simplicity sake, we will make the password input field a standard text field and display our password.

Bind a new function to handle form submission

To change the behavior of form submission to use AJAX instead, we have to make the form run customized Javascript code instead.


  • When the page loads, the $(document).ready() will execute the attached function.
  • Similarly on line 3, we are attaching a function to do something when the form’s submit event is executed.
  • “return false;” on line 5, prevents the browser from reloading the page.

Serialize your data and use $.post to submit your data

Let’s get our code to “do something.” Modify the above Javascript to the following…


You will also need a new PHP page to handle the data being sent. I’ve named my file register.php. For now let’s just have our page echo out the data that it just received.

<?php
print_r($_POST);

Now if you enter some data into form and hit submit, it will send the display the data back in an alert box.

  • We use jQuery’s post (line 5) to submit our serialized form data (line 7) to a PHP page (line 6).
    • When you serialize a form, you are basically preparing all the form elements into a string to be sent with AJAX.
  • On lines 8 to 10, we capture the data echoed from PHP into the data variable and call an alert box to display the data.

Use PHP to send JSON objects back to Javascript

Everything looks good, we have successfully sent our data to our AJAX page, but what if we wanted to display a success or an error message to the user. Thankfully, we can communicate really easily between PHP and Javascript with JSON.

Modify register.php to look like this.

<?php

// Process $_POST data
// ...

$success = TRUE;

if ($success)
    $message = 'Yay! Everything went well!';
else
    $message = 'Doh! Something happened';

// If this is an AJAX call, echo out a JSON object for Javascript
if ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
  $json = array(
              'success' => $success,
              'message' => $message,
              'server'  => $_SERVER
          );

  echo json_encode($json);

// Else, just display the message on a new page
} else {
  echo 'Page was submitted...';
  echo $message;
}
  • On line 13, we are checking the request information to see if this was an XMLHttpRequest. XMLHttpRequest is what AJAX uses to communicate with your server. This if statement will allow us to modify the behavior for AJAX or a standard form submission.
  • On line 21, we wrap our success flags and messages into an array.
  • PHP comes with a JSON encode function that allows us to quickly convert PHP data into JSON data. We just echo out the results and allow the Javascript to get the data back on line 14.
  • From line 24 onwards, we just display the message to the user like you would if you were submitting the form normally.
function(data){
    alert(data);
}

Remember this Javascript from earlier? What I didn’t mention was that whatever is echoed out on the PHP end gets captured in our Javascript variable data. Before it was treating data as a string, but now that we’re using PHP to echo out JSON, we will have to let the $.post function know that the data being returned is JSON. We simply append “json” as the last parameter to the $.post function.

Since data is now defined as a JSON object, we can easily access it’s attributes with dot syntax. For example, you can access the success flag by data.success or the message by data.message.

Use the JSON object to update page

Let’s change this function to display the message in a span with id “ajax-message” and we will change the color of the message depending on the success. Our Javascript would now look like…


  • On lines 8 to 11, we adjust the color with the css function based on the value of data.success
  • On line 12, we update our span with the html function with the value of data.message
  • On line 14, we tell Javascript to treat the data returned as a JSON object

Try toggling between TRUE and FALSE in the register.php page to see what happens.

Conclusion

Submitting form data through AJAX is a really simple process with jQuery. Just follow these simple steps.

  • Create your form in HTML with onsubmit=”return false;”
  • Bind a new function to handle form submission
  • Serialize your data and use $.post to submit your data
  • Use PHP to send JSON objects back to Javascript
  • Use the JSON object to update page

To download the source code click here.

Thanks for reading and leave any questions in the comments.

http://www.georgetruong.com/wp-content/plugins/sociofluid/images/digg_48.png http://www.georgetruong.com/wp-content/plugins/sociofluid/images/reddit_48.png http://www.georgetruong.com/wp-content/plugins/sociofluid/images/dzone_48.png http://www.georgetruong.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png http://www.georgetruong.com/wp-content/plugins/sociofluid/images/delicious_48.png http://www.georgetruong.com/wp-content/plugins/sociofluid/images/technorati_48.png http://www.georgetruong.com/wp-content/plugins/sociofluid/images/google_48.png http://www.georgetruong.com/wp-content/plugins/sociofluid/images/myspace_48.png http://www.georgetruong.com/wp-content/plugins/sociofluid/images/facebook_48.png http://www.georgetruong.com/wp-content/plugins/sociofluid/images/twitter_48.png

19 Comments to “How to submit a form with AJAX in jQuery”

  • Jase says:

    Hey, thanks very much. This really helped me out with a project I’m working on.

  • I’m glad it helped. Feel free to ask me if you have any further questions. :-)

  • Erol says:

    Well you should upgrade your form. Because right now, somebody with disabled JS wont be able to post form.

    Its better that you have fully working “normal” form and then add JS. So Just add an action to form and then use that parameter in your JS code. Then you will be able to use same JS for multiple forms with different actions :D

    Bye

  • dr.ashoor says:

    Thanks very much.

    But if you could plz, Complete and explain how to use JQuery form validation plugin. :)

  • @Erol You are absolutely right. I wrote this to quickly illustrate the concept of posting via AJAX and didn’t consider if JS is disabled. Thanks for your excellent eye on detail!

    @Dr. Ashoor That sounds like a great idea for another blog post. Thank you!

  • The form and code has been updated to degrade gracefully when JS is disabled. Thanks again Erol.

  • behnish says:

    hello dear..

    i am using a slider in which where forms are being submitted and i want to submit the forms with jquery how i will implement this ..where forms will be submitted on a click button…plz help

    thanks

  • Just used this today. Thanks!

  • Hey Behnish,

    What kind of slider are you using? One way that I can think of is to have your slider update hidden fields in the form. Then when you post, the serialize() function will grab that and send it to the page. I’m not 100% confident on this because I haven’t used sliders too much in the past.

    Good luck!

  • Bakudan says:

    Maybe it is stupid but the clipboard is only available for IE. I mean the little text above the code.

  • Hmm… I am not sure I just used Google Syntax Highlighter and haven’t messed with the code. Maybe you should file a bug report with the project.

  • pre says:

    how about validation, I’ve searched every where. I need a form that combines everything, user name availability check, field validation and ajax submission. What’s up with all the half ass ajax scripts, come on people step your game up.

  • pre,

    Thanks for taking the time to read this article and I’m sorry you find it “half assed.”

    The truth is it is impossible to write how to articles that cater to every single circumstance in an application or script. Programming tutorials are written to be as simple as possible so that users can get the general idea and use that knowledge to create something. It would be a huge disservice to readers to recommend a cookie-cutter method and offer a copy-paste script to do X. Great programmers learn quickly and adopt new ideas creatively to solve their unique challenges.

    Regarding backend field validation, user name availability checking, et cetera, the foundation is there to submit any form data to PHP, have it do some processing, and return JSON back for jQuery to process. I would urge you to reread the code in Use PHP to send JSON objects back to Javascript. All you need to do is populate the $json hash with your calculations / validations / database checks.

    Frontend validation is another beast. There are tons of ways to do this including a jQuery plugin or you can write your own functions to validate fields with regular expressions.

    Regards,
    ~ GT

  • Ari says:

    Right now if javascript is disabled, it simple just echo’s the failure/success message on a new page …
    I dunno if this is correct approach, but i have the form post to itself via its action parameter (so if javascript isn’t enabled, it posts to itself). You can do error checking at the top of the script there and then easily flag/populate your fields on the page to resubmit corrections if there are errors (versus a generic error message on another page which this tutorial has).
    The downside to this is that the logic for server-side error-checking is pretty much copy and pasted from the ajax page (although I’m sure someone smart can figure out a way to create a way to reduce duplicate code which may be interesting followup article). Just throwing that out there.

    Enjoyed your article … never thought of checking with $_SERVER['HTTP_X_REQUESTED_WITH'], although shouldnt trust that data entirely as it can be spoofed, right (asking, not sure myself)?

  • I have to confess that I didn’t really consider writing this tutorial with graceful degradation when JavaScript is disabled. It’s not an excuse but the majority of user’s have Javascript enabled and have rarely considered non-JavaScript users. But I do like your idea of checking for JavaScript and posting to a separate action.

    Not entirely sure about $_SERVER['HTTP_X_REQUESTED_WITH']. Seems like a lot of frameworks and other guys use this to check for XMLHttpRequests. If there is a better and more secure way to check, please let me know.

    Thanks for the feedback and the insight.

  • Guest says:

    Great article, thanks.

  • Guest says:

    How would I do this on a wordpress theme page like single.php?

    doesnt seem to like the url when i just put url: single.php,

  • Ryan says:

    Nice post… Serialize, that’s a beautiful method…

    Also, @pre, - you’re a moron! especially before complaining when this is practically laid out for you… notice this is a ‘how to’ article, not a ‘here is a plug-in for doing exactly what i want on my site, i cant believe you didn’t read my mind and do it the way i think you should have, because i couldn’t code it myself, in fact the ctrl + c, and v buttons on my keyboard are worn out’ article! Why don’t you post something useful somewhere instead of complaining about it when somebody else does?

Post comment

What I do

Expertise PHP
Internet Engineering
Build highly scalable web applications in Ruby on Rails, PHP MVC, and Python / Django.
Expertise2
Frontend Programming
Create shiny websites with CSS, (X)HTML, Javascript, AJAX, and Web 2.0 sugar.
Expertise3
LAMP Administration
Apache, MySQL, Memcache, CRON jobs, and the magic sauce that make web apps tick.
Expertise4
iPhone / OS X Development
Develop applications for iPhone and OS X in Objective-C / Cocoa for kicks and giggles.

View my portfolio »

Popular Posts

Archives

About me

My name is George. I am a Software Engineer with about three years experience developing in open-source internet technology. I currently live and work in Los Angeles, California.

I am currently a Ruby on Rails developer. But the majority of my experience has been in PHP. I have also dabbled in C# / ASP.NET and Python / Django for various projects.

View my résumé or contact me today.

Get in touch!

You may either use my contact form, or send and email to me directly at george@georgetruong.com.

You could also try to reach me at 626-817-2633.

Twitter LinkedIn Google Facebook