Auto suggest text box using PHP and jQuery - php

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.

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.

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.

AJAX post to database

I have looked at other questions and cannot find the answer to why this isn't working. I am following a tutorial online. Here is my code:
HTML file:
<!DOCTYPE HTML>
<html>
<head>
<title>AJAX Test</title>
</head>
<body>
<h4>Enter an Item</h4>
<input type="text" id="item" /><br />
<input type="button" id="button" value="Submit" /><br />
<div id="content"></div>
<script type="text/javascript" scr="ajax.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
</body>
</html>
JS file:
$('#button').click(function() {
var item = $('#item').val();
$('#content').text('Loading...');
$.post('ajax.php', { item: item }, function(data) {
$('#content').text(data);
});
});
PHP file:
<?php
include 'db.php';
if (isset($_POST['item'])) {
$item = $_POST['item'];
$sql = mysql_query("INSERT INTO items(item)VALUES('$item')");
if ($sql === true) {
echo "Inserted into database";
} elseif ($sql ==== false) {
echo "Error inserting into database";
}
}
?>
I don't see what I'm doing wrong. The tutorial has the same code. Thanks for your help.
moonwave99 is right (I'm not sure why the downvotes).. and also the scr="ajax" should be src="ajax" in your html and should be put in head or even before. Other reason may be the position of ajax.php to the site, maybe declaring whole URL will help :
$.post('http://wholeurl/ajax.php', {
item: item
}, function(data) {
$('#content').text(data);
});
Hope this helps, if not please specify error.
Well i dont know if i can help you:
You have some mistakes on your code
The elseif condition is not ====(4) just ===(3)
The ajax.js file should be after the jquery library
The src attribute is not scr.
And of course the URL of the jquery library should start with http:// because is an external resource.
The mysql_query() function should have the conection variable, Example:
mysql_query("[query here]", $connect);
Beside any other error you may get, you should import jQuery before your script:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="ajax.js"></script>

Edittext filter error on php and html

while entering the data in the textfield on the browser, it should fetch the data from the database and display accordingly. (ex: like google).
Here is my php code:
<?php
mysql_connect("localhost","root","MobixMySQL") or die(mysql_error());
mysql_select_db("filter") or die(mysql_error());
$partialStates = $_POST['partialStates'];
$states = mysql_query("SELECT name FROM list1 WHERE name LIKE "%$partialStates%"");
while($state = mysql_fetch_assoc($states)) {
echo "<div>".$state['name']."</div>";
}
?>
And below is my html code:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function getStates(value){
$.post("getStates.php",{partialStates:value},function(data){
$("#results").html(data);
});
}
</script>
</head>
<body>
<input type="text" onKeyUp="getStates(this.value)" >
<div id="results"></div>
</body>
</html>
Pls suggest me where am wrong....!!!
Error with your quotes in the SQL...along with injection. Check out PDO for future development
$partialStates = mysql_real_escape_string($_POST['partialStates']);
$states = mysql_query("SELECT `name` FROM list1 WHERE `name` LIKE '%$partialStates%'");
EDIT
Since you're using jQuery trying changing your onkeyup event. If you are still getting errors use something like FireBug or your browsers javascript debugger to check for further errors. Try the following (untested):
<script type="text/javascript">
$(document).ready(function() {
$('input#myFilter').keyup(function(event) {
$.post("getStates.php",{partialStates:$(this).val()},function(data){
$("#results").html(data);
});
}).keydown(function(event) {
if (event.which == 13) {
event.preventDefault();
}
});
});
</script>
</head>
<body>
<input type="text" id="myFilter">
<div id="results"></div>
Try this
$states = mysql_query("SELECT name FROM list1 WHERE name LIKE '%".mysql_real_escape_strings($partialStates)."%'");
Instead of this
$states = mysql_query("SELECT name FROM list1 WHERE name LIKE "%$partialStates%"");

jQuery UI autocomplete doesn't work with jQuery 1.6 and jQuery UI 1.8.12. Why? [Edited] now works partially

I'm trying to use jquery ui autocomplete but its not working. I just pasted an old code I have, that works in other application that uses with jquery 1.4.4 and jquery ui 1.8.6. Now I'm trying to use with jquery 1.6 and jquery ui 1.8.12. The date picker is working but the autocomplete just blinks the field and shows nothing. Here are the codes:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>autocomplete</title>
<link rel="stylesheet" href="css/jquery.ui.all.css" type="text/css" media="screen" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#m').autocomplete({
source: "search.php",
minLength: 2
});
$('#dt').datepicker({
dateFormat: 'dd/mm/yy',
showWeek: true,
firstDay: 1,
changeMonth: true,
changeYear: true
});
});//jQuery End
</script>
</head>
<body>
<div class="ui-widget">
<label for="m">uf: </label>
<form>
<input type="text" id="m" name="m" />
<input type="text" id="dt" class="dt" />
</form>
</div>
</body
</html>
<?php
include_once 'inc/mysqli.php';
//$term = strtolower($_REQUEST['term']); //this was not needed
$term = $_REQUEST['m'];
$query = "SELECT * FROM cidades WHERE nome LIKE '%$term%'";
$result = $mysqli->query($query);
$arr = array();
while($obj = $result->fetch_assoc()) {
$arr[] = $obj['nome'];
}
//echo '('.json_encode($arr).')'; //for jsonp
echo json_encode($arr);
?>
I have no patience with this code and probably is because of it that I can't see the mistake.
[Edited]
If I make a simple SELECT statement the autocomplete works but not in the way I want. It shows all the results and I want it to show the filtered results by the $term variable which doesn't work. It will become very slow when it starts to search the real table with more than 9000 entries.
Is search.php in the same folder as this page?
Have you checked the network tab of firebug to see if search.php is being called correctly and returns the correct results?

Categories