Can't build Autocomplete textbox in PHP - 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
}
});
});

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

Auto Suggest module

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.

How to use jquery autocomplete to load data from mysql database?

I want to make one search box which display list of matched records from database related to which we have type in our box,
I have Use Jquery's Auto Complete.
That's OK, but I want to select records from my database Table instead manually give it in var availableTags.
I want to get records from DB in var availableTags in following code..
here is my code with Smarty Templates.....
My Html:(searchh.tpl)
{block name=head}
<title>Untitled Document</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/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.2/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
}
$(function() {
var availableTags = [
"Python",
"Ruby",
"Scala",
"Scheme"
];
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
{/block}
{block name=body}
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags" />
</div>
{/block}
My php :(searchh.php)
<?php
include("include/config.inc.php");
$pArray = 0;
$search = isset($_POST['search']) && ($_POST["search"] != "") ? $_POST['search']:'';
if($search != '')
{
$query="select * from party where partyName like '%$search%' ";
$result = mysql_query($query);
$pArray = array();
$n = 0;
while ($row = mysql_fetch_array($result))
{
$pArray[$n]['partyId'] = $row['partyId'];
$pArray[$n]['partyName'] = $row['partyName'];
$n++;
}
}
include("./bottom.php");
$smarty->assign("search",$search);
$smarty->assign("pArray",$pArray);
$smarty->display('searchh.tpl');
?>
If Anybody can help, It will very grateful to me.
Thanks..
change your url path like {$smarty.server.PHP_SELF | dirname}.balanceAj.php
and you use get method in ajax function and get data using post method.
If you use get method to send data (for get data $_GET[])
and Post method using (for get data $_post[])
You have not referenced your php file from the javascript. "remember to point to the exact location of the php file as in the example below"
`$( "#tags" ).autocomplete({
source: "/searchh.php"
});

How to retrieve the database values to jquery auto complete box through php page

I am a newbie to jQuery; I want to get the data from a database to auto-complete a text box.
I have coded the PHP to get the values from the database. How can I get these PHP values in a jQuery page?
This is the script:
<script>
$(function() {
var Theaters = [
"PVR",
"SCR",
"MTR"
];
$( "#tags" ).autocomplete({
source: Theaters
});
});
</script>
This is the PHP page:
<?php
mysql_connect("localhost", "root") or die (mysql_error ());
mysql_select_db("theaterdb") or die(mysql_error());
$strSQL = "SELECT * FROM theaters";
$rs = mysql_query($strSQL);
while($row = mysql_fetch_array($rs))
{
echo $row['theater_name'] . "<br />";
}
mysql_close();
?>
How can I do this?
Use ajax for this purpose.
<html>
<head>
<title>Untitled Document</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('#radioid').click(function() {
$('#txtDoorStyle').val($(this).val());
});
});
</script>
</head>
<body>
<input type="radio" id="radioid" value="Door Half Transom (011)" name="doorstyle">
<input type="text" value="" id="txtDoorStyle" name="txtDoorStyle" >
</body>
</html>>
you have two choices either two load this autocomplete options upfront in which case you store the data that you have retrieved from the dB in a hidden field after serializing the data to a string and in your javascript you parse it back to an array using str.split(",")
or
you could make an ajax request when the user starts typing and then retrieve the data as a string and then parse it to an array and then pass it to the autoComplete api. You can read about jquery ajax here

Categories