WCJ WCJ - 3 months ago 8
Ajax Question

AJAX: Display value from table in datase with <select> tag (incomplete submit)

I have a problem with my code.. when I'm submitting value of the in getinv.php it is submitting incomplete value for example, when I click '2016-08-27' it only returning '2016'..

My question is, How do I submit this with exact value I want..?

Pls. Help!

Here's my code:

index.php



<!DOCTYPE html>
<html>
<head>
<script>
function showProd(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","getinv.php?q="+str,true);
xmlhttp.send();

}
</script>
</head>
<body>



<form>
<select name="date" onchange="showProd(this.value)">
<option value="">Select date here:</option>

<?php
$con = mysqli_connect('localhost','root','admin','posinventory');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"ajax_demo");
$sql="SELECT DATE FROM inventory WHERE DATE != DATE(NOW()) GROUP BY DATE DESC;";
$result = mysqli_query($con,$sql);

while($row = mysqli_fetch_array($result)) {

echo "<option value='".$row[0]."'>".$row[0]."</option>";
}

mysqli_close($con);
?>


</select>
</form>
<br>
<div id="txtHint"></div>

</body>
</html>





getinv.php



<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}

table, td, th {
border: 1px solid black;
padding: 5px;
}

th {text-align: left;}
</style>
</head>
<body>

<?php
$q = intval($_GET['q']);
echo $q;
$con = mysqli_connect('localhost','root','admin','posinventory');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM inventory WHERE DATE = '".$q."'";
$result = mysqli_query($con,$sql);

echo "<table>
<tr>
<th>tran_num</th>
<th>date</th>
<th>item_num</th>
<th>inv_quan</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row[0] . "</td>";
echo "<td>" . $row[1] . "</td>";
echo "<td>" . $row[2] . "</td>";
echo "<td>" . $row[3] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html>





This is my table

Answer

It seems that the date is being submitted correctly. Inside getinv.php, you are using intval, which returns the integer value from date and since date starts with a digit, it returns all digits up to but excluding the first dash, so '2016-08-27' becomes '2016'.

Replace

$q = intval($_GET['q']);

with

$q = $_GET['q'];
Comments