Ajax, PhP and MySQL simple applications
I hate JavaScript (…there I said it!) but with the implementation of Ajax, I’ve had to put in some effort into understanding it somewhat. After much studying up - or rather copy and paste errors - on Ajax and some clever google searches, I finally completed a long awaited project. A simple booking engine / sans shopping cart that’s easy to use and to my surprise, quite easy to code The following tutorial requires that you have-working knowledge of PHP and MySQL, the Ajax won’t be of much importance since we’re only going to use simple XMLHttpRequests which will allow for the dynamic controls.
From this tutorial, you should be able to quickly build simple web applications, or expand the code into something larger. So let’s begin:
The User Interface (UI)
Remember to always keep your UI’s simple, it’s the most important part of your web application. You want to invite users to use your application not scare them off with gadgets and dohickies. Simple is always the way to go. So let’s first design a basic form for our users to interact with:
That’s it for the form, you can add more elements to it later, for now and to ease up on my typing time, we’ll settle for the above.
<form method=”get”>
<label for=”item”>item</label>
<select name=”item_id” id=”item_id>
<option value=”1″>item 1</option>
<option value=”2″>item 2</option>
<option value=”3″>item 3</option>
<option value=”4″>item 4</option>
</select>
<label for=”checkIn”>check in</label>
<input type=”text” name=”checkIn” id=”checkIn” />
<label for=”checkOut”>check out</label>
<input type=”text” name=”checkOut” id=”checkOut” />
<label for=”adults”>adults</label>
<input type=”text” name=”adults” id=”adults” />
<label for=”button”> </label>
<input type=”button” name=”book_button” id=”book_button” onclick=”javascript:createAction();” />
</form>
Of course you can pretty it up with your own CSS styles, there are so many css tutorials out there, so not going to waste your time in writing up something fancy for you. You can see my css via the working demo for this engine by clicking here.
The next thing we want to do is create a space for our itinerary, what you will need is a simple <div> tag with a unique id. We’ll call it “itinerary” for the purpose of this tutorial.
<div id=”itinerary”>
</div>
Great! Now that we have our form and page completed, it’s time to set up our Ajax and Javascript.
Create an XML connection based on your browser. The following function is widely used in tutorials throughout the www, it basically creates the ajax connection based on the users browser: ActiveXObject for MSIE or XMLHttpRequest for FireFox and Opera.
function createXMLHttpRequest() {
var xmlhttp;
if(window.XMLHttpRequest) {
try {
xmlhttp = new XMLHttpRequest();
} catch(e) {
xmlhttp = false;
}
} else if(window.ActiveXObject) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
xmlhttp = false;
}
}
return xmlhttp;
}
Now let’s utilize our function and make the connection:
var req = createXMLHttpRequest();
Our next javascript function makes the connection to a PHP script on the server. The PHP script does most of the work for your application and we’ll get to that real soon.
This function does exactly what it says, using the above connection assigned to the variable “req” we can now connect directly to our PHP script.
function sndReq(action) {
req.open('get', 'phpreqpage.php?action='+action);
req.onreadystatechange = handleResponse;
req.send(null);
}
Here we use the open connection “req” and request the page “phpreqpage.php” while passing the variables held in “action” via a form get method.
When the connection has been made, we pass the response from our PHP script back to our browser. (Ajax at work…) We then pass this response off to another function which handles the returned values from our PHP script.
function handleResponse() {
if(req.readyState == 4){
var response = req.responseText;
document.getElementById('itinerary').innerHTML = response;
}
}
This function checks if the process was completed and our returned data to our div tag “itinerary” we created earlier. Sounds pretty easy doesn’t it? These three functions are the main functions you’ll need to handle most any simple Ajax application, in fact - with just these three functions, and some simple PHP code, we already have a very basic Ajax application - but Basic is so boring!!!
function createAction() {
var vars = document.getElementById('item_id').value+'|'+
document.getElementById('checkIn').value+'|'+
document.getElementById('checkOut').value+'|'+
document.getElementById('count').value;
sndReq(vars);
}
I’m so lazy when it comes to JavaScript, so I wrote this quick function above that will pull the information from our form, when completed and send it off to our sndReq function we made earlier. (remember the +Action?) well here’s our Action variable in one simple JavaScript function. Click here for the code to the above script.
We’ll come back to our JavaScript above later, to add in more functions later. For now, let’s hit our PHP script and get something going.
The PHP Script
<?php
debug($_REQUEST);
function debug($array) {
echo "<pre>\n";
print_r($array);
echo "</pre>\n";
}
?>
This is a little script I use a lot to test my post or get arrays. We'll use it for this tutorial so you can see how this process is working so far. Perfect, everything is working just fine. Have you tested your application yet? With the current code above (Ajax, JavaScript and PHP) we should already have a working script - test it, if it's not working. Go back up through the tutorial and make sure you have everything copied exactly. You might also want to look at your form id's as those are important to the script. It needs to have a value to pass through. Once you have your application working, you can continue on.
We'll be using PHP Sessions to control our engine, so you might want to add in the session_start(); calls to both your form page and your php script page as both pages will be necessary to create active sessions.
Before we begin our PHP Script, we first need to get our MySQL database ready. We'll make a simple database to save on time.
MySQL Database
Begin by creating a table called items - this is a basic table with a very basic structure. You can copy my SQL dump below while you’re following this through.
CREATE TABLE `items` (
`item_id` INT NOT NULL AUTO_INCREMENT ,
`itemName` VARCHAR( 100 ) NOT NULL ,
`startDate` DATE NOT NULL ,
`endDate` DATE NOT NULL ,
`rate` DATE NOT NULL ,
PRIMARY KEY ( `item_id` )
) Now that we have our database table up and running, it’s time for us to work on our PHP script, I generally like to class up my php functions, just because it’s pretty. Pretty code is important to me! We start off with our current phpreqpage.php which we created earlier. Organize it a bit so we have a good space to work on. Here’s what my page looks like now (yes.. I’m actually working on a new engine as I write this. )
<?php
session_start();
$go = new engine;
$go->debug($_REQUEST);
class engine {
function dbcnx() {
$cnx = mysql_connect(”server”,”user”,”password”)
or die(”Can’t connect to mysql I guess you supplied bad information”);
$cdb = mysql_select_db(”database”,$cnx)
or die(”Can’t select database”);
}
function debug($array) {
echo “<pre>\n”;
print_r($array);
echo “</pre>\n”;
}
}
?>
Let’s go back to our JavaScript functions we made earlier, specifically createAction() - we passed on some values from the form to this function and now we need to do something with it. The values we passed on where seperated with “|” so now we need to parse our vars with php explode or split functions: so we add on another function to our PHP class as follows:
function cleanVars($vars) {
$cleanVars = explode(”|”,$vars);
return $cleanVars;
}
I ran a quick debug() test:
$cleanArray = $go->cleanVars($_REQUEST[action]); //get me a clean array
$go->debug($cleanArray);
and received my array back. You should have received the same thing as well, if not - go back and check your work. On an off-note: I make it a point to debug my code every step of the way, whenever I code I use the “vim editor” on an SSH connection live on the server, so the massive debugging for me isn’t so nutty.
Now that you have the simple engine working, you can now see how easy it is to expand the software with some PHP code and additional JavaScripting.Here’s my entire PHP code, which you can pull from, and the demo is here to test the software in action:
Posted in Ajax