Tutorial: AJAX to PHP with Prototype

Ajax is everywhere on the web now. If you were late to the game then here is the quick and dirty. Ajax is fancy talk for making calls to the server with out refreshing the page. It is basically a small stack with in your application. Today we are going to build an extremely simple version of an Ajax web app.

Getting Ready

Before we begin we need a few prerequisites.

  • Access to a web server with at least apache and php installed
  • Basic understanding of php
  • Basic understanding of javascript
  • Basic understanding of html (do i have to ask?)

Ok, if those are all good grab the latest stable prototype js library. Prototype allows us to do more with less code which is always a good thing.

Overview

Ok so now we are ready to start building our simple application. So what will it be? I was gonna do the boring but standard multiple two numbers or print “Hello World” but instead lets do a mad libs application. It will take a few words and select a random sentence and fill in the blanks. Sounds fun? Lets begin

Server-Side Code

Somewhere on your sever create the following directory structure.

/madlib/js
/madlib/calls
/madlib/calls/get_madlib.php
/badlib/index.html

Upload the prototype.js (i usually rename it from prototypejs-x.x.js) file into the js directory so we dont have to worry about it later. Now for the server-side code.

<?php

#
#   get_madlib.php - return our madlib sentence
#

// our words from the user
$noun = strip_tags($_REQUEST['noun']);
$verb = strip_tags($_REQUEST['verb']);
$adj  = strip_tags($_REQUEST['adj']);

// our sentences to fill in
$sentence = array
(
‘The %s %s next to the %s unicorn.’,
‘A large %s went and %s a %s building.’,
‘An old %s always %s on a %s wizard.’
);

// get a random index from the sentence array
$r = rand(0, (count($sentence)-1));

// fill in the blanks
$madlib = sprintf($sentence[$r], $noun, $verb, $adj);

// send back our madlib
echo $madlib;

?>

This code is pretty straight forward I hope. First we clean up the input, setup our available sentences, generate a rand number in the range of the sentence indexs, fill our blanks in, return the new sentence.

You can preview this is working buy going to the url and just manually passing in the values.

/madlibs/calls/get_madlibs.php?noun=duck&verb=punched&adj=hairy

You should get a wacky sentence back. Now on to the client side!

Client-side Code

This is were I expected the new stuff to be introducted. I hope the code and comments speak for themselves. Here is the code for the page.

<html>

<head>
<title>
Madlib Maker
</title>
</head>

<script src=”./js/prototype.js” type=”text/javascript” language=”javascript” charset=”utf-8″></script>
<script type=”text/javascript” language=”javascript” charset=”utf-8″>
// <![CDATA[

// function to get the mad lib from server
function getMadlib()
{

// our words from the below elements
var noun = $('noun').value;
var verb = $('verb').value;
var adj  = $('adj').value;

// url we want to call
var url = './calls/get_madlib.php?noun=' + noun + '&verb=' + verb + '&adj=' + adj;

// use prototype ajax request to get response from url
new Ajax.Request(url,
{
method: 'get',
onSuccess: function(transport)
{
$('madlib').update(transport.responseText);
}
});

}

// ]]>
</script>

<body>

<h1>Madlib Maker</h1>

<div id=”madlib” style=”color: red;”></div>

<br />

Noun : <input type=”text” name=”noun” value=”" id=”noun” /> <br />
Verb : <input type=”text” name=”verb” value=”" id=”verb” /> <br />
Adjective: <input type=”text” name=”adj” value=”" id=”adj” /> <br />
<input type=”button” value=” Generate ” id=”button” onclick=”getMadlib();” />

</body>

</html>

I am going to skip the obvious stuff and assume you know the basics. So lets just talk about getMadlib() function.The following line shows how to easily use prototype to grab an input elements value:

var noun = $(’noun’).value;

Then we just point to the location of our working php script:

var url = ‘./calls/get_madlib.php?noun=’ + noun + ‘&verb=’ + verb + ‘&adj=’ + adj;

Next we use the prototype Ajax.Request function. The first paramater is the url, the second is a collection of options. These options include functions to call on different return states. In this example we only worried about onSuccess, but there is also, onFailure, and onComplete.

// function to get the mad lib from server
function getMadlib()
{

// our words from the below elements
var noun = $(’noun’).value;
var verb = $(’verb’).value;
var adj  = $(’adj’).value;

// url we want to call
var url = ‘./calls/get_madlib.php?noun=’ + noun + ‘&verb=’ + verb + ‘&adj=’ + adj;

// use prototype ajax request to get response from url
new Ajax.Request(url,
{
method: ‘get’,
onSuccess: function(transport)
{
$(’madlib’).update(transport.responseText);
}
});

}

In our onSuccess return state we update the madlib div element to contain the text our php script return in the transport object.

Lastly when we click our button it calls the above function and BAM! You have got an Ajax powered madlib web application.

This was my first tutorial so I hope it was written ok. Any comments are welcome.

Download

You can download the whole project here.

Now What?

  • Try improving the script add more sentences, more words available
  • Try using the Form.serialize function here to get all the element inputs at once
  • Try playing with the onFailure (make script fail),  onComplete return states

Resources

A New Beginning

I have just removed all old files to my site and started over again. I was very busy with real life for a long time and didn’t have time to put up any content. But finally I have reprioritized and set some time aside to get some content up here.

The content will focus on development with a bias toward web development and linux. I plan to throw some desktop programming in here as well especially in the areas where the web and the desktop overlap using some new technologies like AdobeAIR and Mozilla Prism.