I would like to send data to a MySql DB from a form via AJAX and a PHP script. I can get it perfect using option selection in the form, but I simply cannot get it using a text submit form.
First what works:
HTML Form:
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
</select>
</form>
.js Scipt:
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();
}
PHP Script:
<?php
$q=$_GET['q'];
$con = mysql_connect('localhost', 'root');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ajax_demo", $con);
$sql="SELECT * FROM emp WHERE id = '$q'";
$result = mysql_query($sql);
$i = 0;
echo "<table class=\"table-master\">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysql_fetch_array($result))
{
$i++;
echo "<tr class=\"d".($i & 1)."\">";
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);
?>
What I want to do is to have a text field in my HTML which will be filled out by the user when the user hits 'submit', that information gets passed into the js script containing the AJAX segment, gets queried by the DB and the results are outputed into my DIV.
Where I think I am going wrong - cannot use onchange obviously in the form when using a text form for submition. Has to be onsubmit !? The js script works so therefore I think my AJAX part is fine. The PHP script also works but again, everything breaks down as soon as I try to get text input from the form. Perhaps my js script is not set up to capture the incoming text form variables!? Any help / guidance would be appreciated.