IDIOT DEVELOPER

Autosuggestion with JQuery , Ajax, and PHP
Autosuggestion with JQuery , Ajax, and PHP

Autosuggestion feature is used to provide the auto suggestion for users while entering input. In this we are going to work on this. We are going to make autosugestion application that is going to suggest us the name of the user form the database.

 

JQuery Autocomplete function is called on the key-up event of the input field. This function requests PHP for the name of the user via AJAX by sending the value of the input field. In PHP, it reads names from the database that starts with the keyword entered by the user.

 

User Table

 


CREATE TABLE `users` (
`uid` int NOT NULL PRIMARY KEY AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`email` varchar(100) NOT NULL UNIQUE,
`password` varchar(100) NOT NULL
);

 

First of all put some data in the table, so that you can see some data in the autosuggestion.

 

JQuery AJAX Code

This code is used to fetch data from the php file through AJAX. The benefit of using AJAX is that the data can fetch without loading the webpage.

You also need to add jquery.min.js file in the webpage.

 


<script src="jquery.min.js"> </script>
<script type="text/javascript">
  $(document).ready(function(){
    $("#search").keyup(function(){
      var search_data = $(this).val();
      var data = 'search=' + search_data;

      if(search_data == ''){
      }else{
        $.ajax({
          type: "POST",
          url: "search.php",
          data: data,
          cache: false,
          success: function(html){
            $("#result").html(html).show();
           }
        })
      }
    return false;
  });
});
</script>

 

The search query is send to the search.php file. Now we need to connect to the database, and search for the information. We are going to use PDO for the database connection.  Finally we just need to display the data.

 

index.php

 


<!DOCTYPE html>
<html>
<head>
  <title> Autosuggestion with JQuery, Ajax and PHP | PHP | Idiot Developer</title>
  <script src="jquery.min.js"> </script>
  <script type="text/javascript">
    $(document).ready(function(){
    $("#search").keyup(function(){
      var search_data = $(this).val();
      var data = 'search=' + search_data;

      if(search_data == ''){
      }else{
        $.ajax({
          type: "POST",
          url: "search.php",
          data: data,
          cache: false,
          success: function(html){
            $("#result").html(html).show();
            }
         })
       }
     return false;
  });
});
</script>

<style type="text/css">
.main{
  background:#f2f2f2;
  width:500px;
  height:500px;
  padding:10px;
  box-shadow:1px 5px 10px #ccc;
  margin-left:auto;
  margin-right: auto;
}

.h3{
  font-family: sans-serif;
  font-size:20px;
  color:#000;
  font-weight:500;
  padding-bottom:20px;
  border-bottom:1px solid #ccc;
}

.input{
  padding:10px;
  width:480px;
  border-radius:0px;
  border:1px solid #ccc;
}

#result{
  background: #fff;
  width:500px;
  border:1px solid #ccc;
  border-radius:0px;
  margin-top:-1px;
  display:none;
}
</style>
</head>

<body>

<div class="main">
  <h3 class="h3" align="center"> Autosuggestion with JQuery , Ajax, and PHP </h3>
  <form autocomplete="off" onsubmit="return false;">
  <label for="search"> Search </label>
  <input type="text" name="search" id="search" class="input">
  </form>

  <div class="result" id="result"></div>
</div>

</body>
</html>

 

search.php

This file helps the user in finding the data . This file contains two functions get_db() and get_search_data(). The get_db() helps user in connecting with the database. The get_search_data helps user in getting the data from the database, and then displaying it.

 


<?php
@session_start();
define('HOST', 'localhost');
define('USERNAME', 'root');
define('PASSWORD', '');
define('DBNAME', 'tut');

function get_db(){
  try{
    $db = new PDO( 'mysql:host=' . HOST . '; dbname=' . DBNAME, USERNAME, PASSWORD );
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    return $db;
  }catch(PDOExecption $e){
    echo 'Connection Failed: ' . $e->getMessage();
  }
}

function get_search_data($search){
  $db = get_db();
  try{
    $stmt = $db->prepare("SELECT * from users WHERE name LIKE :search");
    $stmt->bindValue("search", '%' . $search . '%', PDO::PARAM_STR);
    $stmt->execute();
    $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $db = null;
    return $data;
  }catch(PDOException $e){
    echo "Error" . $e->getMessage();
    return false;
  }
}

$search = mysql_real_escape_string($_POST['search']);
$data = get_search_data($search);
foreach($data as $d){
?>

<style type="text/css">
.result-opt{
  color: #333;
  background:#fff;
  padding:10px;
  cursor: pointer;
  border-top:1px solid #ccc;
}
.result-opt:hover{
  background:#ccc;
}
</style>

<div class="result-opt">
<?php echo $d['name']; ?>
</div>
<?php } ?>

Leave a Reply

Your email address will not be published. Required fields are marked *