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!