I’m trying to use Ajax, PHP, and MySQL together to make a form element, drop-down style select input be able to select an option and have the ajax sent data through the script to the database and back to the page to a separate div. I have most of the code for this figured out. My issue now is this.
I have three drop-down menus that 1 would like to have go to this script. It would then go to three different $GET scripts depending on which menu it was selected from.
<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>
The three select elements I have are accompanied with onchange functions.
<select name="characters" onchange="showCharacter(this.value)">
<select name="towers" onchange="showTowers(this.value)">
<select name="enemies" onchange="showEnemies(this.value)">
The PHP code I have for this script is this:
<?php
include("dbinfo.inc.php");
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
mysql_select_db("db1801445-main", $con);
$sql="SELECT * FROM user WHERE id = '".$q."'";
$result = mysql_query($sql);
$q=$_GET["q"];
echo "<table border='1'>
<tr>
<th>Name</th>
<th>Description</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['Description'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
Idk how else to do this so can you guys help me?
I agree that using jQuery would make your life easier, but to address your question:
You could make that JS code more general so it would be easier to reuse:
And then change you PHP do this:
?>
And back on the frontend: