Expanding the AJAX and PHP 30 Second Tutorial Code
Recently I uploaded an online golf course teetime booking center for a client. The system, allows users to visualize their tee time itinerary as they progress through their booking. A visitor simply selects a golf course and tee time as well as the number of rounds they wish to purchase, add it to their itinerary and continue on, whether they wish to add more golf courses or just book their tee times.
When it comes to PHP and Perl I can probably code just about any web software out there, but in this case, I wanted to add some AJAX and JavaScript fun and build a nice little web gadget and so entered my AJAX research. I browsed through several websites offering AJAX and PHP tutorials, and finally found one called the “30 Second AJAX Tutorial“, I’m pretty sure that almost everyone has attempted this tutorial themselves. The tuturial was pretty basic, and offered the AJAX and JavaScript as well as supporting PHP code but, beware, copy the AJAX direct from the demo code, as the code copy on the tutorial itself isn’t working.
I sat for a few minutes, looking through the magic code. It was such a neat little gadget, and I wondered about the many possible gadgets and fun I could create. I received a call from a client that same morning, who asked if I could redo their online booking engine for Las Vegas Golf Tee Times. Alright a new project!
I began my little gadget by first researching a bit more on the IE and FireFox issues behind AJAX, and found additional AJAX code that supported both browsers - google at work. (Love it!)
function createXMLHttpRequest() {
var ua; if(window.XMLHttpRequest) {
try { ua = new XMLHttpRequest(); }
catch(e) { ua = false; }
} else if(window.ActiveXObject) {
try { ua = new ActiveXObject(”Microsoft.XMLHTTP”);
} catch(e) { ua = false; } }
return ua;
}
Chucked out the 30 second tutorial XMLHttpRequest function and replaced it with the one above. Okay, so now I have my cross-browser AJAX connection and some additional code. I needed more… So I pulled out the php booking class I had for the previous booking system, and created a new php page to utilize these classes and return the response through AJAX. Here’s a snippet of the booking engine class:
class bookings {
function dbc() {
$cnx=mysql_connect(blah, blah,blah);
$sdb=mysql_select_db(blah,$cnx);
}
#The magic PHP get rate sql query
function getRate($item) {
$this->dbc();
$arrs[name]=$arrs[rate]=array();
$sql = “select golfCourse, rate from table where id=’”.$item.”‘”;
$dbi = mysql_query($sql) or die(mysql_error());
$r = mysql_fetch_object($dbi);
array_push($arrs[name],$r->golfCourse);
array_push($arrs[rate],$r->rate);
return $arrs;
}
#Add in some simple PHP Session assignments
function recordSessions($vars) {
if(!$_SESSION[mycart]) {
$_SESSION[mycart] = array();
}
list($item,$sdate,$edate,$nbr) = explode(”|”,$vars);
$itemarray=$this->getRate($item);
$string = $itemarray[name][0].”|”.$itemarray[rate][0].”|”.$teetime.”|”.$date.”|”.$qty;
array_push($_SESSION[mycart],$string);
}
#Let’s add in more simple functions
function getTotal($nbr,$rate) {
return $nbr*$rate;
}
}
I won’t get complicated on the PHP code this is just the basics to get you started. I now have my simple booking engine class set up in PHP and I can now connect to the server through both IE and Firefox, now I need to do more magic and get this thing rolling.
I went back to the 30 second ajax tutorial and added in the rest of the JavaScript and AJAX functions to my .js file, if you notice, I didn’t use the 30 second tutorial code in it’s whole, I have this issue with using JavaScript and prefer to do all parsing in PHP, all I want JS to do, is return and print the string to my web page and nothing more
//create the connection
var req = createXMLHttpRequest();
//send the request to the server PHP file
function sndReq() {
var action = getElementById(’golfCourse’).value;
var action = action + ‘|’+getElementById(’date’).value;
var action = action + ‘|’+getElementById(’teetime’).value;
var action = action + ‘| +getElementById(’golfers’).value;
req.open(’get’, ‘phpRequestPage.php?action=’+action);
req.onreadystatechange = handleResponse;
req.send(null);
}
//handle the response from the server
function handleResponse() {
if(req.readyState == 4){
var response = req.responseText;
document.getElementById(’itinerary’).innerHTML = response;
}
That’s all the code I needed (sans the security and validation.) I built a simple webform requesting the user to select a golf course, the date and time and the number of tee-times he will need. Aside the form (Think CSS 2 columns) I initiated a div tag and assigned it an ID “itinerary”.
<div id=”itinerary”>
…gave the form a method of “get”
<form method=”get”>
…assigned the select drop boxes with ID’s I need the JavaScript to pull from using getElementByID()
<select id=”golfCourse”> (example. do the same for all your form elements id=”whatever”)
The submit button is simply a button
<input type=”button” name=”book_button” value=”add to itinerary” id=”book_button”
onclick=”javascript:sndReq();” />
Great! I now have working AJAX, JavaScript and a PHP Class to handle things on the back end, it’s now time to pull them alltogether. So I open a new document and named it phpRequestPage.php and worked in some lines:
#call up the PHP Class
$go = new class bookings;
$go ->recordSessions($_REQUEST[action]); #all the parsing done and session created
Some basic looping thrugh the sessions
for($i=0; $i list($item,$rate,$teetime,$date,$qty) = explode(”|”,$_SESSION[mycart][$i]);
echo “<div class=’itinHeader’>$golfCourse</div>\n”;
echo “<div class=’itin’>Date: $date</div>\n”;
echo “<div class=’itin’>TeeTime: $teetime</div>\n”;
echo “<div class=’itin’>Rounds: $qty</div>\n”;
echo “<div class=’itin’>Total: “.$go->getTotal($qty,$rate).”</div>\n”;
echo “<div class=’clearFix’><br/></div>\n”;
}
PHP page returns the above echo’s to that AJAX, JavaScript function sndReq() which pushes the response to handleResponse() and the magic appears inside the Itinerary div tag.
Using the above scenario’s you can easily build this booking engine yourself, add in a few more PHP functions to handle deletions and edits support it with more JavaScript and you are all set to go. If you need some help getting through parts of the above code, just drop me a line, I’ll be happy to point you in the right direction. But please, do not attempt the above without some basic PHP and JavaScript knowledge!
Posted in Code