I'm trying to pull a value from my database when a select value is selected. This select is also populated from the same database.
To be clear, I'm new to AJAX requests and don't really understand what I'm doing wrong. All I get is blank when a value should appear.
This is my html form:
function showStock(str) {
if (str == "") {
document.getElementById("stockValue").innerHTML = "";
return;
} else {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("stockValue").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "getstock.php?q=" + str, true);
xmlhttp.send();
}
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php $link=mysqli_connect( "localhost", "root", "", "cocktails"); // Check connection if($link===f alse){ die( "ERROR: Could not connect. " . mysqli_connect_error()); } ?>
<script src='menu.js'></script>
<form action="addstock.php" method="post">
Product:
<br>
<select name="products" onChange="showStock(this.value)">
<option value="">Select a product:</option>
<?php $sql=m ysqli_query($link, "SELECT name FROM inventory ORDER BY name"); while ($row=$ sql->fetch_assoc()){ echo "
<option value=\ "".$row[ 'name']. "\">" . $row['name'] . "</option>"; } ?>
</select>
<br> Stock Value:
<div id="stockValue">
<b>0</b>
</div>
</form>
</body>
</html>
This is my php file:
<!DOCTYPE html>
<html>
<head> </head>
<body>
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','root','','cocktails');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql="SELECT * FROM inventory WHERE name = '".$q."'";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
echo $row['stock'];
mysqli_close($con);
?>
</body>
</html>
</div>