Jump to content

Seat Booking PHP + AJAX?


ramzanrozali

Recommended Posts

Hi coders!I am new to php and ajax itself but I have go through most of php and ajax tutorial at w3schools. It helps me a lot and now I wan to try out to create simple seat booking or reservation using PHP and AJAX but I have some problems.The tutorials that I have referred to do these are:PHP Seat Bookinghttp://dayg.wordpress.com/2008/04/17/php-1...rvation-system/AJAX Database Tutorialhttp://www.w3schools.com/php/php_ajax_database.aspSo what I have done is to have files:seat.php ->indexcheckseats.js -> jsbookseats.php ->to check at server sideHere’s the code for references:Seat.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Booking Tickets</title><script src="checkseats.js"></script></head><body><?php//connect to database and the details.$con = mysql_connect('localhost', 'xxxxx', 'xxxx');if (!$con) { die('Could not connect: ' . mysql_error()); }mysql_select_db("bus-ticketing", $con); /* Create and execute query. */$querySeats = "SELECT * from bt_seats order by rowId, columnId asc";$result = mysql_query($querySeats);$seatColor = null;$tableRow = false;//echo $result;echo "<table width='100%' border='0' cellpadding='3' cellspacing='3'>";while (list($rowId, $columnId, $status, $updatedby) = mysql_fetch_row($result)){	if ($prevRowId != $rowId) {		if ($rowId != 'A') {			echo "</tr></table></td>";			echo "\n</tr>";		}		$prevRowId = $rowId;		echo "\n<tr><td align='center'><table border='1' cellpadding='8' cellspacing='8'><tr>";	} else {		$tableRow = false;	}		if ($status == 0) {		$seatColor = "lightgreen"; 	}else if ($status == 1) {		$seatColor = "red";			} else {		$seatColor = "red";	}	echo "\n<td bgcolor='$seatColor' align='center'>";	if ($status == 0){		echo '<input type="button" value="' . $rowId . '' . $columnId . '" id="Seat" onClick="checkSeat(this.value)">';	}	else { echo "<br />Booked";}	echo "</td>";		}echo "</tr></table></td>";echo "</tr>";echo "</table>";/* Close connection to database server. */mysql_close();?><select name="selType" id="selType">		  <option selected>Select Type</option>		</select>   </body></html>

Checkseats.js

// JavaScript Documentvar xmlHttpfunction checkSeat(str){ xmlHttp=GetXmlHttpObject()if (xmlHttp==null) { alert ("Browser does not support HTTP Request") return }var url="bookseats.php"url=url+"?seats="+strurl=url+"&sid="+Math.random()xmlHttp.onreadystatechange=stateChanged xmlHttp.open("GET",url,true)xmlHttp.send(null)}function stateChanged() { if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {  document.getElementById("selType").innerHTML=xmlHttp.responseText  } }function GetXmlHttpObject(){var xmlHttp=null;try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); }catch (e) { //Internet Explorer try  {  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");  } catch (e)  {  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");  } }return xmlHttp;}

Bookseats.php

<?php//connect to database and the details.$con = mysql_connect('localhost', 'xxxx', 'xxxxx');if (!$con) { die('Could not connect: ' . mysql_error()); }mysql_select_db("bus-ticketing", $con);//after select departure		//prompt type after select the button$seats=$_GET["seats"]; //input from seats button$querySeat="SELECT type FROM bt_seats WHERE rowId = '".$rowId."' AND columnId = '".$columnId."' ";$resultSeat = mysql_query($querySeat);while($row = mysql_fetch_array($resultSeat)) { echo '<option value="' . $row['type'] . '">' . $row['type'] . '</option>';  }		mysql_close();?>

Sequence:1. I will click the available button2. if the seat status is available (0), 3. it then will ask (as in picture) the type whether it for adult or childen in selection menuscreenshot.jpgProblems:1. The output, to display type is not working after I click the button (the picture is dummy)2. How can I resend data for seats no ($rowId$columnId) and types to be stored to database and3. then the box will then turn to red? (how to refresh the table automatically)Thanks for reading and I hope I can learn from you guys soon :)Thanks a lot.p.s: snapshot of database sampledatabase2.jpg

Link to comment
Share on other sites

1. The output, to display type is not working after I click the button (the picture is dummy)
Have you checked the return value from the PHP page? You can load the PHP page manually, or alert the responseText property, or use a debugger like Firebug to check the response from the XMLHttpRequest. It would probably be worth it to use a debugger anyway to look for other errors that may be happening.
2. How can I resend data for seats no ($rowId$columnId) and types to be stored to database and
You're already sending the check to get the dropdown options, you can send whatever information you want and have the PHP script do whatever you want with the data (e.g. store it in a database). You would need to create the XHR object and send another request to update the database.
3. then the box will then turn to red? (how to refresh the table automatically)
It will probably be easiest to remove the button, change the background color to red, and add the Booked text. Here's a function to remove all of the children from an element:
function removeChildren(el){  for (var i = el.childNodes.length - 1; i >= 0; i--)	el.removeChild(el.childNodes[i]);}

To change the background color you can access the style property, and you would use innerHTML to add the text, or use appendChild and append a new text node.document.getElementById("id").style.backgroundColor = "red";

Link to comment
Share on other sites

You're already sending the check to get the dropdown options, you can send whatever information you want and have the PHP script do whatever you want with the data (e.g. store it in a database). You would need to create the XHR object and send another request to update the database.
Does it mean i should create the XHR over here such as;
function GetXmlHttpObject(){var xmlHttp=null;var xmlHttp2=null; //the new XHR?

So how about to check the browser? should it be like this?

try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); xmlHttp2= new XMLHttpRequest(); //the new XHR? }etc...

Thanks a lot for your help :)

Link to comment
Share on other sites

I posted a couple functions from quirksmode.org that are useful with XHR pages here:http://w3schools.invisionzone.com/index.php?showtopic=5
I tried to change the js so i can create many XHR as you suggest:
//file name: checkseat.jsfunction checkSeat(str){ var xmlHttp=createXmlHttpObject();if (xmlHttp==null) { alert ("Browser does not support HTTP Request") return }var url="bookseats.php"url=url+"?seats="+strurl=url+"&sid="+Math.random()xmlHttp.onreadystatechange=stateChanged xmlHttp.open("GET",url,true)xmlHttp.send(null)}function stateChanged() { if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {  document.getElementById("selType").innerHTML=xmlHttp.responseText  } }var XMLHttpFactories = [	function () {return new XMLHttpRequest()},	function () {return new ActiveXObject("Msxml2.XMLHTTP")},	function () {return new ActiveXObject("Msxml3.XMLHTTP")},	function () {return new ActiveXObject("Microsoft.XMLHTTP")}];function createXmlHttpObject() {	var xmlhttp = false;	for (var i=0;i<XMLHttpFactories.length;i++) {		try {			xmlhttp = XMLHttpFactories[i]();		}		catch (e) {			continue;		}		break;	}	return xmlhttp;}

The problem was it does not prompt the selection menu, but already update the database to 1 (booked).Here's the snapshot of problem that happen:test-1.gifI tried to check the error with firebug but I am not really know how to use it properly...Here's the code of bookseats.php as references:

//prompt type after select the button$seats=$_GET["seats"]; //input from departure//prompt the type: Adult and Children automaticallyif ($seats != "0"){ echo '<option selected>Select Type</option>';echo '<option value="Adult">Adult</option>';echo '<option value="Children">Children</option>';}

Thanks in Advanced.

Link to comment
Share on other sites

With Firebug, click on the Net tab to see the requests for the page. The XHR tab on the Net tab will show the AJAX requests that go out and come back. If you have that tab open and press one of the buttons you should see a new request show up there. Click on the new request and then click on the Response tab for it to see the information that the server sent back. That information is what is going into the dropdown box. If you see an error for PHP then there's a problem on the page, or if you see no output then the PHP isn't sending anything back. Or else you should see the options listed.

Link to comment
Share on other sites

Firstly before i continue to learn, i would like to say Thanks justsomeguy :) You have teached me "fishing" and this is very interesting :)Alrigth. So the selection menu is working and now i want to update the database.So what i have done is:add event called updateSeat to seats.php:

<select name="selType" id="selType" onchange="updateSeat(this.value)"></select>   <span id="updated"></span>

add functions:

//update status and type to databasefunction updateSeat(str){ xmlHttp2=createXMLHTTPObject()if (xmlHttp2==null) { alert ("Browser does not support HTTP Request") return }var url="bookseats.php"url=url+"?updateSeat="+strurl=url+"&sid="+Math.random()xmlHttp2.onreadystatechange=stateChanged2 xmlHttp2.open("GET",url,true)xmlHttp2.send(null)}function stateChanged2() { if (xmlHttp2.readyState==4 || xmlHttp2.readyState=="complete") {  document.getElementById("updated").innerHTML=xmlHttp2.responseText  } }

and finally update the database:

//to prompt type after button click$seats=$_GET["seats"]; // click the seat//prompt the Adult and Children type automaticallyif ($seats != "0"){ echo '<option selected>Select Type</option>';echo '<option value="Adult">Adult</option>';echo '<option value="Children">Children</option>';}//input from type, update the status$updateSeat=$_GET["UpdateSeat"]; //select type such as adult or children$queryUpdate="UPDATE bt_seats SET status='1', type='".$updateSeat."' WHERE seatId = '".$seats."' ";$resultUpdate = mysql_query($queryUpdate);echo 'updated ready';

The database is updated with the correct seatId and status set to 1. But the type value is not updated.However if i change the type to='".$seat."', so it will become:

$queryUpdate="UPDATE bt_seats SET status='1', type='".$seats."' WHERE seatId = '".$seats."' ";

, it will update the database with seat value successfully. So what is the problem?I think that $updateSeat=$_GET["UpdateSeat"]; is not working. What's your opinion?Besides, the success will echo "updated ready", along with other echo such select menu which is incorrect.I think its somewhere around the function at checkseats.js as i don't understand how to use the function that recommended as here:http://w3schools.invisionzone.com/index.php?showtopic=5Here's the snapshot of problem:error-1.gifThanks in advanced.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...