AJAX Forms with JQuery

As requested I have written this tutorial so that readers understand exactly how to produce AJAX forms with JQuery. Now, let’s dive into the weird and wonderful world of JQuery!

Now as always you need to import your JQuery with this in your head tag:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js" type="text/javascript"></script>

Now we need to make our form so within the body tag we add our form:

<form name="thisform">

<input type="text" id="myfirstname">
<input type="text" id="mylastname">
<input type="submit" value=" Submit " id="submit_AJAX">

Now comes the difficult part:- making the JQuery function and binding it to the form. You will want to put this within your head tag as well:

 $(document).ready(function() {
    $("#submit_AJAX").click(function () { 
          //get our values
          var first = $("#myfristname").val();
          var last = $("#mylastname").val();

	  var dataString = 'first='+ first + '&last=' + last;

          //shows you whats being sent
	  alert (dataString);
	    type: "POST",
	    url: "somepage.php",
	    data: dataString,
	    success: function(callback) {
		    if(!callback) return;
                    //alerts the user of the echo in the php

And lastly we need to make a simple PHP (server-side) page to handle the AJAX request:

     $_COOKIE['AJAXFORM'] = $_POST['first']." ".$_POST['last'];
     echo "cookie updated";    
     setcookie("AJAXFORM", $_POST['first']." ".$_POST['last']);
     echo "cookie made";

And that should do it 🙂 You will now have an AJAX form. I should explain in this example I have binded the function via the onclick on the submit button, however, to have many forms simply turn the AJAX function into its own separate function then on the form submit just make it point to that function:

<form name="thisform" onsubmit="AJAXFUNCTION()">

Enjoy 🙂


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s