Auto Suggest module - php

I am working on a search bar for my website which has an auto-suggest feature. I implemented this using php, ajax, jquery, and mysql.
Now I want that the result should be displayed as a link, so if user clicks on a result it will redirect the user to that page.
I also want the search result in this format:
My code is:
index.php
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Autocomplete textbox using jQuery, PHP and MySQL by CodexWorld</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#skills" ).autocomplete({
source: 'search.php'
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="skills">Skills: </label>
<input id="skills" autofocus="">
</div>
</body>
</html>
search.php
<?php
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'search_demo';
//connect with the database
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
//get search term
$searchTerm = $_GET['term'];
//get matched data from skills table
$query = $db->query("SELECT skill,category FROM skills WHERE skill LIKE '%".$searchTerm."%' ORDER BY skill ASC");
while ($row = $query->fetch_assoc()) {
$data[] = $row['skill'];
}
//return json data
$var = json_encode($data);
echo $var;
?>
My database has three fields id, skill, and category.
The current result is:

You have two options. First one is to extend the jqueryUI autocomplete widget, with the widgets factory. Second one is to create your own autocomplete script, which is in fact simple and is good for learning.

Related

how to autocomplete bootstrap php mysql ajax from database

autocomplete not working i want fetch data from mysql database like google option my file not working not showing any thing when we key down select data from sugested option
please sugest some good code
my code is not running
it is not working now sir
and auto select is not showing similar answer
this is link where showing but not selecting any data under key selection
this is link where show nothing
<!DOCTYPE html>
<html>
<head>
<title></title>
<!--my file not working auto complete address from database-->
<!--code inclide file of botstarp -->
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<!--code of auto fetch-->
<script>
$(document).ready(function () {
$('#Country').typeahead({
source: function (query, result) {
$.ajax({
url:"autoselect_jquery5.php",
data:'query=' + query,
dataType:"json",
type:"POST",
success: function (data) {
result($.map(data, function (item) {
return item;
}));
}
});
}
});
});
</script>
</head>
<body>
div class="container" style="width:600px;">
<h2 align="center">Autocomplete Textbox using Bootstrap Typeahead with Ajax PHP</h2>
<label>Search Country</label>
<input type="text"name="country"id="country"autocomplete="off"placeholder="Country" />
</div>
</body>
< /html>
<!--second file which fetching data from from database -->
// autoselect_jquery5.php file for fetch code
<?php
include 'database.php';
if (isset($_POST['query'])) {
$search_query = $_POST['query'];
$query = "SELECT * FROM transporter WHERE address LIKE
'%".$search_query."%' LIMIT 12";
$result = mysqli_query($link, $query);
$data = array();
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$data[] = $row["address"];
}
echo json_encode($data);
}
}
?>
}
for autocomplete, you can use typehead.js its works with the bootstrap check below ex.
How do we set remote in Typeahead.js?
You have some wrongs, I explain you in the comments in your code.
I hope that I can help you. I copied your code and I fixed it.
It is working now. Try it and comment me.
Steps:
1) Import the database file (on your local server).
Link database: https://drive.google.com/drive/u/1/folders/1JhXXPQ4QHsHssTbpdnhL_cBOrnK7Q3nB
2) Copy in a folder of local server the file autocomplete.html.
<!DOCTYPE html>
<html>
<head>
<title></title>
<!--my file not working auto complete address from database-->
<!--code inclide file of botstarp -->
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<!--code of auto fetch-->
<script>
$(document).ready(function () {
$('#country').typeahead({ // Your #Country ID is different that you using in input
// #Country <>
source: function (query, result) {
$.ajax({
url:"database.php",
data:'query=' + query,
dataType:"json",
type:"POST",
success: function (data) {
result($.map(data, function (item) {
return item;
}));
}
});
}
});
});
</script>
</head>
<body>
<div class="container" style="width:600px;">
<h2 align="center">Autocomplete Textbox using Bootstrap Typeahead with Ajax PHP</h2>
<label>Search Country</label>
<input type="text"name="country"id="country"autocomplete="off"placeholder="Country" />
</div>
</body>
</html>
3) Copy in same folder the php code.
<?php
$host = 'localhost'; //This is your host, if you working locally your host will be localhost
$user = 'root'; //The name of the your user in localhost server
$pass = 'root'; //The password of the your user in localhost server
$db_name = 'countries'; //The name of the database that you using
$keyword = strval($_POST['query']); //
$search_param = "{$keyword}%";
$conn =new mysqli($host, $user, $pass, $db_name);
$sql = $conn->prepare("SELECT * FROM country WHERE name LIKE ?");
$sql->bind_param("s",$search_param);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$countryResult[] = $row["name"];
}
echo json_encode($countryResult);
}
$conn->close();
?>
4) It's over.

PHP GET ($_GET) always prints name of variable and not value

what I'm trying to do is get the value of the selected term from the autocomplete menu (ui.item.label), store it in a variable and send that value to my database. For that, I have another php file named "proceed.php", which connects us to the database and will insert the data into the table.
But I seem to be stuck at passing the variable "$selected" from look to proceed as no matter what I do, the browser displays $vari, that is, the variable passed here - proceed1.php?var=$vari
Backstory - You may notice that I have assigned the variable vari as apple. Yet, I see only $vari as the output on the browser and not apple.
Any help will be deeply appreciated.
Thank you very much.
look.php
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#route" ).autocomplete({
source: 'search.php',
select: function( event , ui ) {
$selected=ui.item.label;}
});
});
$vari="apple";
</script>
</head>
<link rel="stylesheet" type="text/css" href="look.css" media="screen" />
<body>
<div class="ui-widget">
<label for="route">Router Name: </label>
<input id="route">
<br><br><br>
Proceed
</div>
</body>
</html>
proceed.php
<?php
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'searchrouters';
//connect with the database
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
//get search term
$vari = $_GET['var'];
echo $vari;
?>
UPDATE :
Thank you, the solution provided in the comments worked. But now when I'm trying to get the variable selected's value as :
<?php
$vari=$_GET['selected'];
?>
and then pass it in to the next page as :
Proceed
I get the following error on the browser :
Undefined index: selected in C:\wamp\www\look.php on line 19
You need to modify you code in two places
<script>
$(function() {
$( "#route" ).autocomplete({
source: 'search.php',
select: function( event , ui ) {
$selected=ui.item.label;
$('#btn2').attr({'href':'proceed1.php?var='+$selected});
}
});
});
</script>
<?php
$vari="apple";
?>
and Proceed
and when you need to access the variable just use $_GET['var']
Where ever you want to user php with HTML you need to user the <?php php code here ?>
here is a demo
You can not declare php variable in jquery.
try this
<script>
$(function() {
$( "#route" ).autocomplete({
source: 'search.php',
select: function( event , ui ) {
$selected=ui.item.label;}
});
});
</script>
<?php
$vari="apple";
?>
and
Proceed
You should change here remove $vari="apple"; from script tag and use it inside php tag
<?php $vari="apple"; ?>
and get variable $vari like this
Proceed

Can't build Autocomplete textbox in PHP

I've been trying to learn how to build an autocomplete textbox that fetches the cities from my database, I use XAMPP so it's mySQL. Following is the code that I picked up from a tutorial and modified according to my needs:
demo.html
<html>
<head>
<title>Autocomplete demo</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#city" ).autocomplete({
source: 'search.php'
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="city">Region: </label>
<input id="city">
</div>
</body>
</html>
search.php
<?php
//database configuration
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'sample_master';
//connect with the database
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
//get search term
$searchTerm = $_GET['city'];
//get matched data from skills table
//"region" is the column from the table I wish to fetch
$query = $db->query("SELECT * FROM cities WHERE region LIKE '%".$searchTerm."%' ORDER BY region");
while ($row = $query->fetch_assoc()) {
$data[] = $row['region'];
}
//return json data
echo json_encode($data);
?>
In xampp I startup the MySQL and Apache server, and then open demo.html from htdocs. The autocomplete feature doesn't work(nothing shows up while I'm typing). What am I doing wrong? Also, the cities DB has excess of 3,00,000 records.
autocomplete default $_GET is $_GET['term'] ,you are called $_GET['city'] so you need to change your $_GET name or you can define your GET name like below..
$(function() {
$( "#city" ).autocomplete({
source: function(r,res){
$.get('search.php',{city:r.term},res,'json');//r is input typing request,res is response result as json
}
});
});

jQuery ui autocomplete ipv4

I'm using the jQuery UI Autocomplete as helper in a form. When I try to use it to search from a list of available IPs it never filter the results, no matter the number of characters (numbers) I type it always returns the complete list.
How can I correct it?
I am using this code http://jqueryui.com/autocomplete/#remote-with-cache
The JSON generated from a PHP file is similiar to this (I have reduced the number of results):
["192.168.3.2","192.168.3.3","192.168.3.4","192.168.3.5","192.168.3.6","192.168.3.7","192.168.3.8","192.168.3.9","192.168.3.10"]
[Edit]
The form page code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Autocomplete - Remote with caching</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<style>
.ui-autocomplete-loading {
background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat;
}
</style>
<script>
$(function() {
var cache = {};
$("#birds").autocomplete({
minLength: 2,
source: function(request, response) {
var term = request.term;
if (term in cache) {
response(cache[ term ]);
return;
}
$.getJSON("tab-ip-autocomplete.php", request, function(data, status, xhr) {
cache[ term ] = data;
response(data);
});
}
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="birds">Birds: </label>
<input id="birds" />
</div>
</body>
</html>
The PHP to JSON code:
<?php
include_once 'conn.php';
INET_NTOA(ipv4) LIKE :ipv4";
$autocomplete = "SELECT * FROM vteste;";
$STH = $DBH->prepare($autocomplete);
$STH->bindParam(':ipv4', $ipv4, PDO::PARAM_STR);
$STH->execute();
$STH->setFetchMode(PDO::FETCH_ASSOC);
$row = $STH->fetch();
/* gera json */
$arr = array();
while ($row = $STH->fetch()):
$arr[] = $row['ipv4'];
endwhile;
$json = json_encode($arr);
echo $json;
?>
When using a remote datasource, the jQueryUI AutoComplete doesn't filter your results - it is down to the script which provides the data to send over only matching results.
From the http://api.jqueryui.com/autocomplete/#option-source:
The Autocomplete plugin does not filter the results, instead a query
string is added with a term field, which the server-side script should
use for filtering the results. For example, if the source option is
set to "http://example.com" and the user types foo, a GET request
would be made to http://example.com?term=foo. The data itself can be
in the same format as the local data described above.

Auto suggest text box using PHP and jQuery

I am trying to do an auto suggest text box using PHP and jQuery however, all the jQuery I am using, basing on the internet has already deprecated. I am not sure if my code is the one not working or the jQuery. Could anyone help me please? :) Thank you in advance!
<?php
session_start();
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>jQuery Autocomplete Plugin</title>
<script type="text/javascript" src="js/jquery-1.4.2.js"></script>
<script type='text/javascript' src="js/jquery.autocomplete.js"></script>
<link rel="stylesheet" type="text/css" href="js/jquery.autocomplete.css" />
<script type="text/javascript">
$().ready(function() {
$("#users").autocomplete("autoCompleteMain.php", {
width: 260,
matchContains: true,
selectFirst: false
});
});
</script>
</head>
<body>
<h2 id="banner">Autocomplete</h1>
<div id="content">
<form autocomplete="off">
<p>
Enter Username <label>:</label>
<input type="text" name="users" id="users" />
</p>
<input type="submit" value="Submit" />
</form>
</div>
</body>
</html>
PHP:
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="aaaa"; // Mysql password
$db_name="maptemp"; // Database name
$con = mysql_connect($host,$username,$password) or die(mysql_error());
mysql_select_db($db_name, $con) or die(mysql_error());
$q = strtolower($_GET["q"]);
if (!$q) return;
$sql = "select username from users where username LIKE '%$q%'";
$rsd = mysql_query($sql);
while($row = mysql_fetch_array($rsd)) {
$cname[] = $row['username'];
}
echo json_encode($cname);
Replace
$q = strtolower($_GET["q"]);
with
$q = strtolower($_GET["term"]);
because as i know jQuery auto Complete pass term.
You should declare your array in your PHP script : $cname = array();
And as Dipesh Parmar said, jQuery uses "term" parameter.
No need to encode the result in JSON otherwise at front have you parse it. so make a html in php and echo it so you get result in html format.

Categories