AJAX db with PHP

JavaScript related questions should go here.
Post Reply
lakc
Posts: 32
Joined: Fri Oct 21, 2011 6:05 pm

AJAX db with PHP

Post by lakc »

[syntax=php]<script>
function showRooms(str)
{
var xmlhttp;
if (str=="")
{
document.getElementById("resultTable").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("resultTable").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php?r="+str,true);
xmlhttp.send();
}
</script></head>

<body>
<?php
require("db_connect.php"); //Database connection

$r=$_GET["r"];

//Get all matching roomtypes posted after not more than 14 days.
$sql="SELECT * FROM room WHERE room_posteddate >= (SELECT SUBDATE( CURRENT_DATE, INTERVAL 14 DAY ) AS LASTDATE ) AND room_posteddate <= CURRENT_DATE AND room_type = '".$r."'";

$result = mysql_query($sql);

echo "<table border='1'>
<tr>
<th>PostCode</th>
<th>Rent/week</th>
</tr>";

while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['room_postcode'] . "</td>";
echo "<td>" . $row['room_pwk'] . "</td>";
echo "</tr>";
}
echo "</table>"; mysql_close($dbconn);

?>

<div class="roomtype_results"><form action="">
<select name="roomtype" onchange="showRooms(this.value)">
<option selected="selected" value="">Select a room type:</option>
<option value="single">Single Room</option>
<option value="double ">Double Room</option>
</select></form>

<br><div id="resultTable">Room results will be listed here...</div></div></body></html>[/syntax]

I get the error called undefined index r after db connection set. If seperate the php code into a seperate .php file it works.

How can I make all the code work in the same php file witout seperation??.
User avatar
jacek
Site Admin
Posts: 3262
Joined: Thu May 05, 2011 1:45 pm
Location: UK
Contact:

Re: AJAX db with PHP

Post by jacek »

Essentially, you cant. You could have the php bit check for the form data and only try to use it if it exists.

No offence, but this code is pretty terrible. You should look into using function to separate your logic type code from the html part.

Also you should try to use more valid html, a lot of browser will have trouble processing this.
Image
Post Reply