Jump to content

PHP + ajax help


sasori

Recommended Posts

hi, am trying to learn how php + ajax works, but this example from w3schools website doesn't work for me :(,

i have re-written the code manually (twice) and I ended up copy pasting. but still it doesn't show any data from my db

4vpe2w.jpg

 

html code

<html>
<head>
<script type="text/javascript" src="selectuser.js"></script>
</head>
<body>
<form>
Select a User:
<select name ="users" onchange="showUser(this.value)">
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>
<br />
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>

 

the ajax code

 

var xmlhttp;

function showUser(str){
xmlhttp.GetXmlHttpObject();
if(xmlhttp == null){
	alert("Your browser does not support Ajax");
	return;
	}
	var url = "getuser.php";
	url=url+"?q="+str;
	url=url+"&sid="+ Math.random();
	xmlhttp.onreadystatechange = stateChanged;
	xmlhttp.open("GET",url,true);
	xmlhttp.send(null);
	}

function stateChanged(){
if(xmlhttp.readyState == 4){
	document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
	}
}

function GetXmlHttpRequest(){
if(window.XMLHttpRequest){
	return new XMLHttpRequest();
	}
	if(window.ActiveXObject){
	return new ActiveXObject("Microsoft.XMLHTTP");
	}
return null;
}

 

 

php code

 

<?php

$q = $_GET["q"];

$con = mysql_connect('localhost','root','mypassword');
if(!$con){
die("Could not connect: " mysql_error());
}

mysql_select_db('ajaxsample', $con);

$sql = "SELECT * FROM user WHERE id ='".$q."'";
$result = mysql_query($sql);

echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";

while($row = mysql_fetch_array($result)){
	echo "<tr>";
	echo "<td>" . $row['FirstName'] . "</td>";
	echo "<td>" . $row['LastName']. "</td>";
	echo "<td>" . $row['Age']. "</td>";
	echo "<td>" . $row['Hometown']."</td>";
	echo "<td>" . $row['Job'] . "</td>";
	echo "</tr>";
	}
echo "</table>";
mysql_close($con);
?>

 

:confused: :'(

Link to comment
https://forums.phpfreaks.com/topic/191945-php-ajax-help/
Share on other sites

Archived

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

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.