Jump to content

first time with ajax...cant get it to work :(


busby

Recommended Posts

hey...im trying to display messages stored in a database on a page using ajax.

 

a user should choose from a drop down list the title of the message and then on selection that message should appear just below.

 

but i cant seem to do it and i dont know why there is no errors in what ive got so far.

 

here is the code for the drop down box where the user would select the title.

 

		<form>
        <select name="users" onchange="showMessage(this.value)">
        <option value="">Select a message:</option>
        <?php while($rows = mysql_fetch_array($results))
        {?>
        <option value="1"><?php echo $rows['heading']; ?></option>
        <?php } ?>
        </select>
        </form>
        <br />
        <div id="txtHint"><b>Message info will be listed here.</b></div>

 

the drop down is successfully populated with the correct titles.

 

here is the javascript in the HEAD of the same page:

 

<script type="text/javascript">
function showUser(str)
{
if (str=="")
  {
  document.getElementById("txtHint").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("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>

 

and here is the php file which is used to display the message upon selection.

 

<?php
$q=$_GET["q"];

$con = mysql_connect('localhost', 'peter', 'abc123');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("ajax_demo", $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>";

 

could someone please take a look at this and see whats wrong? ive spent so long on it. if you could tell me how to correct it it would be great

Link to comment
https://forums.phpfreaks.com/topic/223710-first-time-with-ajaxcant-get-it-to-work/
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.