Wali faizy Wali faizy - 5 months ago 15
Ajax Question

autocomplete in jquery ajax and php5


index.php


<div class="input-group">
<input type="text" class="form-control autosuggest" placeholder="Search for">
<span class="input-group-btn">
<button class="btn btn-info"><span class="glyphicon glyphicon-search"></span></button>
</span>
</div>
<div class="dropdown">
<ul class="result">

</ul>
</div>



jquery/ajax file


$(document).ready(function() {
$(".autosuggest").keyup(function() {
var search_term = $(this).attr('search');
var dataString = 'search_term='+ search_term;
$.ajax({
type: 'post',
url : 'search.php',
data: dataString,
success: function(data) {
alert(data);
}
});
});

});



search.php file


<?php
include 'includes/db.php';

if(isset($_POST['search_term']) && !empty($_POST['search_term'])) {
$search_term = mysqli_real_escape_string($conn, $_POST['search_term']);
$sql = "SELECT name FROM names WHERE name LIKE $search_term%";
$run_sql = mysqli_query($conn, $sql);
while($rows = mysqli_fetch_assoc($run_sql)) {
echo "<li>$rows[name]</li>";
}
}
?>



I am just making a simple autocomple suggestion in php mysql and ajax, my php version is 5 and jquery version is 2,i want to populate my mysql data in autosuggest container,First i am trying to alert the data on page with the help of javascript alert function but thrie is some error,can anyone please review my code


Thank you

Answer

Use quotes arround search variable

 $sql = "SELECT name FROM names WHERE name LIKE '$search_term%' ";