Owaiz Yusufi Owaiz Yusufi - 1 month ago 4
jQuery Question

How to make auto_search using ajax jquery, php and mysql

I have created auto suggest using Javascript AJAX now I want to create auto suggest using Jquery AJAX here is the code I have written using jquery AJAX

This is my indexa.php

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function(){
$("#search_input").keyup(function(){
var txt = $("#search_input").val();
$.get("search.inc.php?search_username="+document.search_form.txt, {suggest: txt}, function(result){
$("searchResults").html(result);
});
});
});
</script>

</head>
<body>

<form id="search" name="search_form" action="<?php $_SERVER['PHP_SELF']; ?> " method="post">

Search For Names : <input type="text" id="search_input" name="search_text"><br/><br/>
<!-- <input type="submit" > -->

</form>

<div id="searchResults"></div>
</body>
</html>


and this is my search.inc.php

<?php

if (isset($_GET['searched_username'])) {
$username = $_GET['searched_username'];
}

if (!empty($username)) {
if (@$db_connect=mysqli_connect('localhost', 'root', '')) {
if (@mysqli_select_db($db_connect,'my_databse')) {

$query_like = "SELECT `user_name` FROM `members_data` WHERE `user_name` LIKE '%". mysqli_real_escape_string($db_connect,$username)."%'";
$query_like_run = mysqli_query($db_connect,$query_like);
$query_num_rows = mysqli_num_rows($query_like_run);
if ($query_num_rows == NULL) {
echo 'No Result Found';
} else {
if ($query_num_rows == 1) {
echo $query_num_rows ." Result found<br/><br/>";
} else {
echo $query_num_rows ." Results found<br/><br/>";
}
foreach ($query_like_run as $searched_members) {
$searched_results = '<a href="anotherpage.php?searched_username='.$searched_members['user_name'].'">'.$searched_members['user_name']."</a><br/>";
echo $searched_results;
}
}
}
}
}
?>


what I am doing worng . Please Help me

Answer

Remove the values from the url and change the key to search_username

Do the following:

 <script type="text/javascript">

 $(document).ready(function(){
  $("#search_input").keyup(function(){
    var txt = $(this).val();
    $.get("search.inc.php", {searched_username: txt}, function(result){
        $("#searchResults").html(result);//don't forget the # for the id
      });
   });
  });
   </script>
Comments