Google trends Public Holidays Coupon Code Code Compiler

Autocomplete dropdown using jquery plugin


Dec 25, 2018

Autocomplete dropdown using jquery plugin

The Autocomplete provides suggestions while you type into the field. Here the suggestions are city names, displayed when at least one characters are entered into the textfield. The datasource is a server-side script which returns JSON data, specified via a function which uses jQuery.ajax() for the source option.

JavaScript Code


<link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet">
<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
 
  $( function() {
      $( "#city" ).autocomplete({
      source: function( request, response ) {
        $.ajax( {
          url: "getCity.php",
          dataType: "jsonp",
          data: {
            city: request.term
          },
          success: function( data ) {
            response( data );
          }
        } );
      },
      minLength: 1,
      select: function( event, ui ) {
        console.log( "Selected value: " + ui.item.value);
      }
    } );
  } );
</script>

  

HTML Code


<div>
<label for="city">City: </label>
  <input id="city" class="ui-autocomplete-input" autocomplete="off">
</div>

CSS Code


table {
 font-size: 1em;
}
 
.ui-draggable, .ui-droppable {
 background-position: top;
}

PHP Code: getCity.php


$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
 
 $c $username, $password, $dbname);
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
$searchTerm = $_POST['city'];
$query = mysqli_query($conn, 'select cityName from city where cityName LIKE "%'.$searchTerm.'%"'); // Get data from Database 
$name = array();
while($row = $query->fetch_assoc()){
       $name[] = $row->cityName;
    }
 echo json_encode($name);

Copyright 2024. All rights are reserved