我正在尝试为我的网站创建Ajax实时搜索。我目前遇到一些麻烦,认为该代码无法正常工作。有人可以帮我:) 我尝试过的查询没有响应的第一个ajax 第二,当我尝试使用search.php时,http请求出错 idk我努力解决了这个问题
我正在使用php 5.6 AJAX jQuery 2.1.3 Bootstrap 4
live.php
<?php include "header.php"; //ajax and jquery script loaded are here?>
<body>
<div class="container">
<label for="ajaxs">Search</label>
<input type="text" name="search_text" id="search_text" placeholder="Search Keyword" class="form-control" /><br>
<div id="result"></div>
<br>
</div>
</body>
</html>
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"search.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#search_text').keyup(function(){
var search = $(this).val();
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
</script>
search.php
<?php
require "koneksi2.php"; //mysql connection are here
$output = '';
if(isset($_POST["query"]))
{
$search = mysq_real_escape_string($_POST["query"],$koneksi);
$query = "
SELECT * FROM bukutamu
WHERE id LIKE '%".$search."%'
OR dari LIKE '%".$search."%'
OR agama LIKE '%".$search."%'
OR email LIKE '%".$search."%'
OR komentar LIKE '%".$search."%'
";
}
else
{
$query = "SELECT * FROM bukutamu ORDER BY id";
}
$result = mysq_query($query,$koneksi);
if(mysq_num_rows($result) > 0)
{
$output .= '
<div class="table-responsive">
<table class="table table-bordered table-hover table-light:hover">
<tr class="thead bg-primary text-white">
<th>No</th>
<th>Dari</th>
<th>Agama</th>
<th>Email</th>
<th>Komentar</th>
<th>Tanggal</th>
</tr>';
$no = 0;
while($row = mysql_fetch_array($result))
{
$no++;
$output .= '
<tr>
<td>'.$no.'</td>
<td>'.$row["dari"].'</td>
<td>'.$row["agama"].'</td>
<td>'.$row["email"].'</td>
<td>'.$row["komentar"].'</td>
<td>'.$row["tglsimpan"].'</td>
</tr>
';
}
echo $output;
}
else
{
echo 'Data Not Found';
}
?>