Reputation: 149
I have a hard time finding my mistake in this code. I have a search bar and I'd use ajax so that the data will fetch automatically.
This is my html file.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="bootstrap4/jquery/jquery.js"></script>
<script>
function loadproducts()
{
var name = document.getElementById("search");
if(name)
{
$.ajax({
type: 'post',
contentType:false,
cache: false,
processData:false,
data: {
products:name,
},
url: 'loadproducts.php',
success: function (response){
$('#product_area').html(response);
}
});
}
else
{
$('#product_area').html("No Product found!");
}
}
</script>
</head>
<body>
<input type="text" name="search" id="search" onkeyup="loadproducts();">
<div id="product_area">
</div>
</body>
</html>
----------
This is my loadproducts.php file
<?php
include('server/connection.php');
if (isset($_POST['products'])){
$name = mysqli_real_escape_string($db,$_POST['products']);
$show = "SELECT product_name,sell_price FROM products WHERE product_name LIKE '$name%' ";
$query = mysqli_query($db,$show);
if(mysqli_num_rows($query)>0){
while($row = mysqli_fetch_array($query)){
echo "<p>".$row['product_name']."</p>";
echo "<p>".$row['sell_price']."</p>";
}
}
}
Ill tried putting alert("called"); function on the ajax success and the alert is activated but still no output show. I also edit the var name = document.getElementById("search");
to var name = document.getElementById("#search");
but it pass straight to the else statement.Can someone site the problem of this code?
Upvotes: 1
Views: 58
Reputation: 44125
Currently, you're accessing the actual HTML element. You want the value, so use .value
:
var name = document.getElementById("search").value;
Or if you prefer, you can simplify this down with jQuery:
var name = $("#search").val();
Upvotes: 2