<div class="row">
<?php
$connection = mysqli_connect('localhost','root','','product-store');
if(isset($_POST['search'])) {
$searchKey = $_POST['search'];
$sql = "SELECT * FROM products WHERE code_no LIKE '%$searchKey%'";
} else {
$sql = "SELECT * FROM products order by code_no desc";
$searchKey = "";
}
?>
<form action="tabledata.php" method="POST">
<div class="col-md-12 col-sm-12 col-xs-12">
<input type="text" name="search" class="form-control" placeholder="Search By Code" value="<?php echo $searchKey; ?>" >
</div>
<br>
<div class="input-group">
<button class="btn btn-success">Search</button>
</div>
<br>
</form>
<br>
<br>
</div>
</div>
</div>
</div>
$(document).ready(function(){ $("#search").keyup(function() { var query = $(this).val(); if (query != "") { $.ajax({ url:"tabledata.php", method:"POST", data:{query:query}, success:function(data) { $('#result').html(data); } }); } $('#searchKey').keyup(function(){ var search = $(this).val(); if(search != '') { load\_data(search); } else { load\_data(); } }); });发布于 2020-01-07 17:27:10
您在输入字段中缺少id
<input type="text" id="search" name="search" class="form-control" placeholder="Search By Code" value="<?php echo $searchKey; ?>" >发布于 2020-01-07 17:36:35
您不仅在输入字段中缺少id,而且也从未在php代码中执行查询并获取结果。和sql注入是可能的,清理您的$searchKey或使用准备好的语句。
也许您也可以将搜索查询放在一个不同的php文件中,并在那里创建您希望返回给ajax函数的html。
也许这会有所帮助:
为您的ajax搜索功能创建一个新的php文件,如searchData.php
<?php //searchData.php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['query'])) {
$connection = mysqli_connect('localhost','root','','product-store');
$searchKey = $_POST['query']; // Needs to be sanitized to prevent sql injections
$sql = mysqli_query($connection, "SELECT * FROM products WHERE code_no LIKE '%$searchKey%'");
if (mysqli_num_rows($sql) > 0) {
// Fetch the rows
$rows = mysqli_fetch_array($sql, MYSQLI_ASSOC);
$html = '';
// Loop through all the rows
foreach ($rows as $row) {
// Create here your html you want to return to your ajax function
}
echo $html;
} else {
// No results, echo html/ text to the ajax function to inform the user
}
}将ajax函数中的url更改为searchData.php,然后ajax函数将获得您在此文件中回显的所有文本/html。
https://stackoverflow.com/questions/59625430
复制相似问题