Category Archives: ajax-basics

Ajax Basics

Basic Ajax usage with X

Over the next several articles I’ll be covering the “Basic Ajax usage with X”, for example “Basic Ajax usage with jQuery”.

The idea is to take the latest stable version of the chosen JavaScript Framework (for example jQuery) and examine what’s required to achieve the most basic Ajax calls.

I’ll be looking at a few things here, notably the ease of use and the minimum required footprint (in regards to download size).

Note that I will not necessary by using Ajax in the traditional sense of the word (i.e. with XML) as the intention of these articles is to strip everything back to the absolute basics.

I’m not 100% certain about all the frameworks I’ll cover now, but I will most certainly be covering jQuery, MooTools, Prototype, dojo, YUI and ExtJS. If I have the time, I may look at some of the newer ones as well.

This post is a living post (I’ll revisit and link up the articles).

Cheers guys!

Simple Ajax using Prototype. Part 2

Ajax Updater – Update a DOM element ID from a Server Script

This example is probably the simplest example you will ever find.
We are going to use the prototype feature ‘ajax.Updater’ (see part one for more details on prototype).

ajax.Updater allows you to specify an element ID and script URL – and whatever the script URL prints will appear in your element ID. Simple as that.

The example below simply returns the Server time each time the button is clicked.

I’m not going to explain this bit by bit as it is just so easy to grasp.

Remember, you will need the prototype library in order to use this!

Here is the HTML/JavaScript code:

 

And now the PHP code:

updateme.php

 

The above example has no real use, but in the real world there are many things which can be done. For example I recently wrote an automatic session log-out script, which automatically kills the session after a given period and send the user back to the login page (very handy for secure sites). I’ll post that script up soon.

Simple Ajax using Prototype. Part 1

This is part of one of many such tutorials covering Ajax with Prototype.

If you do not want to get your hand to dirty with custom Ajax code, then using the extremely handy toolkit from prototype may be perfect.
Prototype is a very well written JavaScript framework/toolkit and come with an Ajax class to make things nice and easy.

In this simple example I’ll show you just how easy Ajax calls are. But you will need to have your own copy of prototype (its free!).

On a side note… if you like fancy JavaScript effects, you can extend prototype with another library called script.aculo.us – I promise, with these you will have endless hours of fun!!

On with the example
I’ve attempted to simplify things as much as possible. In this tutorial we will type some text into a standard form field, hit a button and see the results appear below. In the background, our button click will trigger our JavaScript function, and pass the text through Ajax to a server-side PHP script. This PHP script will write our text back to an other JavaScript function on our page and print the text out on the screen.

First we include our prototype library:

 

Then we create two of our own functions, the first one is the main script which passes our text to the Server (PHP script in this case). The second function handles the response from the PHP script and prints the results to the browser.

 

In the getResponse function above, noticed the function call $(‘result’) – this is a feature of prototype which basically replaces ‘document.getElementByID(‘result’)’.

Yes, that is all we need in terms of JavaScript. I told you it was simple!!

Next we have the form:

 

Nothing fancy with the above. In order to call our JavaScript functions, we are using the ‘onClick’ event of the button.
We are passing in two values here; first the server-side script file ‘parse.php’ and the value we want to send.
We must pass in the paramater name and value (for example: ‘val=myvalue’, just like any querystring!), the parameter name in the case is ‘val’ and the value is the text in our text field. We refer to this value using another prototype function $F() which is really just ‘document.getElementById(‘myval’).value’.

On the server-side, our PHP script takes the value we passed $_GET[‘val’] and prints it back to us as ‘You entered: yourvalue’ (where ‘yourvalue’ is what your entered in the text field!).

parse.php

 

This is a very simple example of using just one of prototypes Ajax features, there are many more to explorer which I will cover soon.

Have fun!

AJAX generic form parser

AJAX Generic Form Parser – With Validation:

In this tutorial I’ll show you a simple method to pass any HTML form through AJAX without the need to hard code all form fields into the JavaScript or Server Side Script. Using this simple piece of JavaScript you can reuse it as is with any form, saving a lot of time. I’ve even added basic validation to certain form element types (which would be expected).

Okay, straight to the main JS code.

 

The JavaScript code above is split into 4 functions, here is an overview of what each function does.

createXMLHttpRequest() – This is the function which will establish the AJAX connection object, this is called as soon as the JS file is loaded.

sendRequest() – This function is the one which is called when the form is submitted. This function requires (passed in) the ‘Form Object’ and the ‘File Name’ of the script which will receive the form data. When this function has been called, it takes the form object and passes it to the JS function getForm() which in turn parses the whole form extracting all the data. sendRequest() then takes the open AJAX connection and passes all the data to the PHP file form processing. Finally when the request from the PHP server script is returned, it writes out the reply to an element on the screen with the div ID ‘results’.

getForm() – This is the magic, this function reads through the whole form and extracts the field data before returning it back to sendRequest(). It handles radio, text, password, textarea, select and checkbox field types. It even looks for validation requests on text, password and textarea fields (which is enabled by using title=”required” in the form element).

Simple :)

Next is a very simple form with a mixture of field types and validation requests (nothing fancy here). Also included at the bottom is the div which prints out the results to the browser.

 

As you can see the form trigger which calls the AJAX actions is set in the button using the onClick method. Also note I’ve added title=”required” to the ‘textOne’ field – this means the user will not be able to submit the form unless this field contains a value.

Finally here is a very stripped down Server script in PHP which takes the form values and returns them formatted back to the JS (you could do anything with the data at this stage!).

process.php

 

You could easily change the above to generate an email or add the form data to a database, the above example will echo out the results which are passed back to the div tag below the form.

There you have it, short and sweet (I hope) – I’ve intentionally kept the example scripts to a minumum but with still enough to be useful. Please feel free to take this and mess around with it.

Have Fun!!

Simple Ajax Functions – Snippets

Basic Ajax Functions
I’ve created a list of very common JavaScript functions for Ajax. They have been created in quick reference fashion and do not contain any fancy stuff. Instead of creating one function which can handle various tasks depending on passed values, they are split into seperate basic task functions. The reason for this is simplicity.

Anyway – here they are. I’ll post the function and give a basic outline of what it does.

This first function is the real important one – it’s the one which creates the object for making the Ajax connection.



Here is the function which sends the request to the server script. This version creats the connection with TEXT and uses the POST method.



Here is the function which sends the request to the server script. This version creats the connection with TEXT and uses the GET method.



Here is the function which sends the request to the server script. This version creats the connection with XML and uses the POST method.



Here is the function which sends the request to the server script. This version creats the connection with XML and uses the GET method.



Now here is the function which retrieves the response from the server script. This version receives the response as TEXT (http.responseText).



Now here is the function which retrieves the response from the server script. This version receives the response as XML (http.responseXML).



This little function can be used to delay the call – handy for forms where you use onKeyUp or onKeyPress to trigger submit action.



Below is just an example form which I used to work with the above functions.





Here is a basic one field worm which used the onKeyUp to trigger the Ajax with the delay.





And finaly here is the element on the page which the Ajax response is writen to.



To put all this together – just pick the first function (createRequestObject() [remember to include the var http.. part above it]). Select the SendRequest function you require and the handle Request which uses the same method. Then add your form and update the form ID’s (remember to have these matching in the javascript!). See the other posts for a full example of these scripts hanging together.