Ajax, I’m coming

After having bought the Pragmatic Ajax book a few weeks ago, today was the day that I finally dipped my toes into Ajaxy waters.

I had to include a newsletter subscription form on shengpfui.de, an e-commerce site that I implemented with OSCommerce. Since this shop system is quite awful to work with from a developers perspective (e.g. it has no templating system – ist all a mess of intermingled HTML and PHP code), the idea of integrating a result page into the system didn’t appeal at all to me.

Enter AJAX and the possibility to update content on-the-fly and in-place. I decided to use the Prototype library and its AjaxUpdater function. It took me a while to figure out everything, since the documentation is a bit sparse. I couldn’t find a comprehensive list of all the function’s arguments, for example. What I ended up with, though, was concise and straightforward:

<script src="/assets/js/prototype.js" type="text/javascript"></script>
<script src="/assets/js/myajax.js" type="text/javascript"></script>

That’s two lines, one for including the libary and one for including the js file that contains the Updater code, which looks like this:

function process() {

 var ajax =  new Ajax.Updater(
	         'result',
			 '/actions/send-nl-subscribe.php',
	         {	method:'post',
			 	parameters: Form.serialize('mailform') + '&ajax=true'
	         }
			);
}

I added the additional “ajax=true” parameter to tell the backend script that this is an AJAX call. I used this to slightly adapt ist output.

The corresponding form is short and sweet, too:

<form action="/actions/send-nl-subscribe.php" method="post" id="mailform" onsubmit="process(); return false">
  <p><input name="address" id="address" type="text" size="30" maxlength="99" />
  <input name="go" type="submit" value="los" style="color:#000; background-color: #fff; border: 1px solid black;"/></p>
</form>
<div id="result"></div>

On submitting the form, the js helper function process() is called, that contains the Ajax updater code. The form action points to a PHP script that checks and processes the submitted address. The result is inserted on-the-fly into the div with id “result” (see the process() function, where this was specified as a parameter).

What I didn’t realise at first is that you have to disable the submit functionality of the form with Javascript, otherwise the form duly redirects to the specified action URL. That’s why I included the return false; as a Javascript onSubmit event handler in the form attributes.
The way I built this, it’s nicely degradable, i.e. it works for people without Javascript, too. They will simply be redirected to the address of the backend processing script, which prints its processing result and gives a link back to the shop.

As an example, this is what it looks like when you don’t specify an address:

Ajaxified form example

So, at long last, I’ve jumped on the bandwagon, too!


About this entry