I'm having trouble with completing an autocomplete function in Jquery with data from database. Whenever I type something I always get 'no results found' message. I want it to display a country name as the user is typing.
jquery.php
<?php
require "database/database.php";
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<link type="text/css" rel="stylesheet" href="CSS/style.css">
<script type="text/javascript" src="jquery/jquery-1.11.3.min.js"></script>
<script src="jquery/jquery-ui.min.js"></script>
</head>
<body>
<form action="" method="post">
<p><label>Country:</label><input type='text' name='country' value='' class='auto'></p>
</form>
<script type="text/javascript">
$(document).ready(function () {
$('.auto').autocomplete({
source:"suggested.php",
MinLength: 2
});
});
</script>
</body>
</html>
This is my suggested.php page:
<?php
require "database/database.php";
$term = trim(strip_tags($_GET['term']));
$data = mysql_query("SELECT * FROM countries WHERE countryname LIKE '%".$term."%'");
while($row = mysql_fetch_assoc($data)) {
$data[] = array(
'label' = $row['countryname'],
'value' = $row['countryname']
);
}
echo json_encode($data);
flush();
}
?>
In the database I have a table named countries and within it countryid, countryname and countryflag. I need to extract only the countryname column.
I've tried using $_GET['term'] and $_REQUEST['term'].
I've tried different tutorials but none of them seems to work.
If you have any suggestions please tell me.
Thank you
It will be delay your execution if you run query in every time when you type,because you can input value as a query condition value!
I can give you some I tested logic is run your query first when document is loaded and store as a json data type,then you can set source data in autocomplete
This can reduce your page delay respond time by sql query running
<form action="" method="post">
<p><label>Country:</label><input type='text' name='country' value='' class='auto'></p>
</form>
<script type="text/javascript">
$(document).ready(function () {
var source = [];
$.ajax({
url : "suggested.php",
data : "GET",
dataType : "json",
success : function(data){
for(var i in data){
source.push(data[i]);
}
}
});
$('.auto').autocomplete({
source: source,
MinLength: 2
});
});
</script>
suggested.php
<?php
require "database/database.php";
$data = mysql_query("SELECT * FROM countries");
$result = array();
while($row = mysql_fetch_assoc($data)) {
$result[] = array(
'label' = $row['countryname'],
'value' = $row['countryname']
);
}
echo json_encode($result);
flush();
}
?>
Related
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.
I want to make a simple search bar. The search bar sends data through JQuery to PHP (which performs the search). The data is sent back to HTML through the callback function. The search functionality is working as it should. However,every time I type in the search input, the whole page duplicates itself. I don't know why it does so. The data is being fetched from a MySQL database.
<?php
session_start();
include("connection/connection.php");
if(isset($_POST['search_term'])){
$search_term = mysqli_real_escape_string($db_connect,htmlentities($_POST['search_term']));
if(!empty($search_term)){
$sql_search = "SELECT first FROM students_register WHERE first LIKE '%$search_term%' ";
$result_search = $db_connect->query($sql_search);
$result_count = $result_search->num_rows;
$suffix = ($result_count != 1) ? 's' : '';
echo "<p>Your search for <strong>" .$search_term. " </strong>has returned <strong>".$result_count."</strong> result" .$suffix. "</p>";
while($results_row = $result_search->fetch_assoc()){
echo "<p><strong>".$results_row['first']."</strong></p>";
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="js/jquery.js"></script>
</head>
<body>
Search: <input id="search" name="search" placeholder="search">
<span id="search_display"></span>
</body>
<script type="text/javascript">
$("#search").keyup(function(){
var search_term = $(this).val();
$.post('test2.php', {search_term : search_term}, function(result){
$("#search_display").html(result);
});
});
</script>
</html>
``
Here I have question is test2.php and your html page also same page?
try with two pages,
<?php // test2.php
session_start();
include("connection/connection.php");
if(isset($_POST['search_term'])){
$search_term = mysqli_real_escape_string($db_connect,htmlentities($_POST['search_term']));
if(!empty($search_term)){
$sql_search = "SELECT first FROM students_register WHERE first LIKE '%$search_term%' ";
$result_search = $db_connect->query($sql_search);
$result_count = $result_search->num_rows;
$suffix = ($result_count != 1) ? 's' : '';
echo "<p>Your search for <strong>" .$search_term. " </strong>has returned <strong>".$result_count."</strong> result" .$suffix. "</p>";
while($results_row = $result_search->fetch_assoc()){
echo "<p><strong>".$results_row['first']."</strong></p>";
}
}
}
?>
And the Html contains another page
<!DOCTYPE html>
<html>
<head>
<title>Index.html</title>
<script type="text/javascript" src="js/jquery.js"></script>
</head>
<body>
Search: <input id="search" name="search" placeholder="search">
<span id="search_display"></span>
<script type="text/javascript">
$("#search").keyup(function(){
var search_term = $(this).val();
$.post('test2.php', {search_term : search_term}, function(result){
$("#search_display").html(result);
});
});
</script>
</html>
The reason is, you are requesting the data from the test2.php, the test2.php has contain also with the html code, So that only it reappear again and again. please try this let me know the results.
This is a two fold question. How do I update the data (without page reload) on the page when the datepicker is changed?
Also how do i pass the selected date to the dtpickerdate in my sql statement?
Here is my example code
<html>
<head>
<link href="../css/jquery/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="../js/jquery-1.9.1.js"></script>
<script src="../js/jquery-ui.js"></script>
</head>
<body>
<?php include("../navbar.php"); ?>
<p>Date: <input type="text" id="datepicker" value="<?php echo date("m/d/Y"); ?>" /></p>
<script type="text/javascript">
$(function() {
$("#datepicker").datepicker();
});
</script>
<table>
<?php
$sqltext = "SELECT * FROM data where startdate=dtpickerdate";
$result = $mysqli->query($sqltext);
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$key."</td>";
echo "<td>".$row['sun']."</td><td>".$row['mon']."</td><td>".$row['tues']."</td><td>".$row['wed']."</td><td>".
$row['thurs']."</td><td>".$row['fri']."</td><td> ".$row['sat']."</td>";
}}
?>
</table>
</body>
</html>
You need AJAX, first thing create a new php file with your query function that will receive a $_POST parameter with the value of the datepicker:
getData.php
<?php
$dtpickerdate = isset($_POST['dtpickerdate']) ? $_POST['dtpickerdate'] : NULL
$sqltext = "SELECT * FROM data where startdate = $dtpickerdate";
$result = $mysqli->query($sqltext);
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$key."</td>";
echo "<td>".$row['sun']."</td><td>".$row['mon']."</td><td>".$row['tues']."</td> <td>".$row['wed']."</td><td>".$row['thurs']."</td><td>".$row['fri']."</td><td> ".$row['sat']."</td>";
}
?>
Now you listen to the change event on your input and use AJAX to call your PHP, when the call completes you update your table:
$('#datepicker').change(function(){
$.post('getData.php',{dtpickerdate : $(this).val()}, function(response){
$('table').html(response);
});
});
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.
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%"");