De-Mystifying AJAX

I remem­ber when I first learned of AJAX, and I remem­ber think­ing: “I’ll never fig­ure that out.” Well, remem­ber when you never thought you’d learn how to remove the under­line on your links with CSS? That proved eas­ier than we thought (we later found out that CSS is an amaz­ingly pow­er­ful pre­sen­ta­tion lan­guage). We need to cut through the need­less lan­guage and get to the meat of AJAX. We don’t need to worry about what the XML­HttpRe­quest object is at this point. Often design­ers only need to know enough to dupli­cate an effect and not the nitty-gritty.

What Is AJAX?

I feel as though a clar­i­fi­ca­tion needs to be made. JavaScript effects are some­times con­fused to be AJAX. If we tog­gle an ele­ment it is an JS effect, but it is not AJAX (although they can be used together). For an exam­ple, the pop­u­lar web­site Digg uses both. When you show “buried com­ments” that is a JS tog­gle and not AJAX, but when you “digg” a story that is AJAX. AJAX is sim­ply pro­cess­ing a request to the server “asy­chro­nously” or “at the same time” as view­ing the rest of the page (which saves us a full page refresh).

JavaScript Frame­works

There are many good JavaScript frame­works that have an AJAX func­tion built-in. The most notable are mootools, script.acolo.us, and jQuery. All are viable options, but for this tuto­r­ial I will uti­lize the mootools framework.

Pro­cess­ing A Form w/AJAX

This tuto­r­ial cov­ers how to process form inputs with AJAX requests. I also decided that I wanted to return a mes­sage to the user upon suc­cess­ful sub­mis­sion. The included ZIP file includes all the nec­es­sary code, but I will paste it here to walk you through it. First, we need to include the mootools framework.

Frame­work Include (in the head)

<script src="js/mootools.js" type="text/javascript"></script>

Form Code

The fol­low­ing code is a sim­ple form with three fields (first/last name, RSVP). Notice the “action” is insert.php; the AJAX must process an exter­nal page. The “id” is used to con­nect the JS func­tion with the form, and the “method” is post. Notice also that the onClick event (on the sub­mit but­ton) is what invokes the function.


<form action="insert.php" id="myForm" method="post"> First Name:
<input name="firstname" type="text" /> Last Name:
<input name="lastname" type="text" /> RSVP: <select name="rsvp"> <option>Select</option> <option value="Accept">Accept</option> <option value="Regret">Regret</option> </select> <input value="Submit" onclick="sendForm()" type="button" /></form>

send­Form() Func­tion (for the AJAX Call)

This is our func­tion that must go right after the form itself. The update option is what will be pop­u­lated on return from the AJAX call (it will be returned in the PHP file). Be sure to replace the text for the db user name, pass­word, and name.

<script type="text/javascript">  function sendForm(){  new Ajax(\'insert.php\',{postBody:$(\'myForm\'), update: \'container\'}).request(); }  </script>

PHP Insert

This opens our con­nec­tion the data­base. Replace the con­nec­tion para­me­ters with your own (username/password/db name). The last echo state­ment will be what is returned and filled in the “con­tainer” div to let our user know that their request was submitted.

$con = mysql_connect("localhost","<dbusername>","<dbpassword>");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}</dbpassword></dbusername>

mysql_select_db("<dbname>", $con);</dbname>

$sql="INSERT INTO RSVP (firstname, lastname, rsvp)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[rsvp]')";

if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}

echo "Thank You $firstname For Your RSVP!";

mysql_close($con)
?&gt;

Updated DIV


So, after pro­cess­ing the form it should return in the con­tainer div: “Thank You [FIRST NAME] For Your RSVP!” Feel free to add some JS effects to make it even prettier!

Down­load Tuto­r­ial Code

10 Comments

  1. Well nice tuto­r­ial for begin­ners. I just hope you will rewrite your PHP code to some­thing more secure and move the db con­nec­tion to a sep­a­rate file.

    Frank on 12.20.06
  2. You’re right, but I made it sim­ple for beginners.

    Chris Poteet on 12.20.06
  3. \“This is our func­tion that must go right after the form itself\”

    Maybe I\‘m wrong, but why right after the func­tion? I know this is for begin­ners, but if I were a begin­ner (or more of one, I sup­pose), I might take this to mean all the time (espe­cially with the ital­ics for empha­sis). It\‘s much eas­ier to cre­ate a js file to include with the func­tion in that, and I think would make things sim­pler in the long run for n00bs. Maybe in part two you could start by explain­ing this. Maybe that was the plan all along

    Nice short tutorial.

    d3vkit on 12.21.06
  4. Hi Chris

    Agreed — it´s a nice tuto­r­ial. But I sug­gest you warn users, that the php script is not safe per se, in case some­one is tempted to use your exam­ple code.

    Thanks!

    Raz

    Rasmus on 12.21.06
  5. In mootools there is a send func­tion for forms. The send func­tion send the form with Ajax.

    $(‘myForm’).send({update: ‘con­tainer’});

    Nir Tayeb on 01.14.07
  6. Hi all,

    Thanks for the tuto­r­ial, but the code in func­tion send­Form() actu­ally has errors.. ;) just change “new ajax” to “new Ajax”

    Palaniraja on 02.21.07
  7. @Palaniraja: Thanks! Changes made.

    Chris Poteet on 02.21.07
  8. My plea­sure ;)

    Palaniraja on 02.22.07
  9. Thanks for your tuto­r­ial.
    It really showed how easy AJAX is with mootools. :-)

    Mike on 03.22.07
  10. Thankyou for this tuto­r­ial. being an expiri­enced PHP / MySQL coder I could see where you were com­ing from in the whole script. Thanks again!

    Steven on 01.06.08

Got Something to Say?

(Required)
(Required)