Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.