jQuery Autocomplete not showing results - javascript

I'm looking for a way to make it so when a user starts typing into a input field, it will start to generate results underneath in a drop down.
For instance, like when you start typing into Google or the Facebook search bar.
What is that actually called?
UPDATE:
I have decided to use jQuery AutoComplete.
I have the following
<form action="" method="post">
<input type="text" class="auto" name="search" autocomplete="off">
</form>
<script>
$(document).ready(function($){
$('.auto').autocomplete({
source:'connect.php',
minLength:1
});
});
</script>
And connect.php
I KNOW I have to sanitize $term before inputting it into my query.
if(isset($_GET['term'])) {
require "db.php";
$con = mysqli_connect("$host","$user","$password","$db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$term = $_GET['term'];
$query = "SELECT `name` FROM `products` WHERE `name` LIKE '%$term%'";
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) {
echo json_encode($row);
}
}
Now when I use chrome tools to inspect the response, It works completely fine, it brings back the data I wanted in a JSON format.
However, for some reason, it states 'No results found' on the page even though there is?

It's called typeahead/autocomplete.
Twitter Bootstrap 2.0 (outdated - not available in 3.0) & jQuery UI have what you require.

You need to get all of the records from database and return them.

I suggest making an ajax request to the server (php script). First you would need an oninput event handler for the text box for the search. The php script will return the records you want. Here is my code:
<input type="text" id="searchBox" oninput="searchTheDatabase(this.value)" value="let us search it'>
<div id="results"></div>
Javascript:
<script type="text/javascript">
function searchTheDatabase(searchText)
{
$.post( "search.php", { searchText:searchText})
.done(function( data ) {
$("#results").html(data);
});
}
</script>
PHP:
<?php
//put your connection code here
$searchText = mysql_real_string_escape($_POST['searchText']);
$searchTextLength = strlen($searchText);
$query = "select * from products where";
//I'm not sure how you search for only the first so many characters, but you can use $searchTextLength to help you
$result = mysql_query($query, $connect);
while($row = mysql_fetch_array($result))
{
echo $row['name'];
}
?>
Let me know if this doesn't work for you and I will do some more coding. :-) good luck!

It's sometimes a part of the UI for the Browser, where it auto completes your fields for you with past entries. There is a HTML5 element called datalist where you can tie that element into the list attribute for an input field to get the same results
<div>Choose a browser from this list:</div>
<input list="browsers" />
<datalist id="browsers">
<option value="Chrome">
<option value="Firefox">
<option value="Internet Explorer">
<option value="Opera">
<option value="Safari">
</datalist>
For this, all you need do is populate datalist's option values with entries from your database. something like this would work ...
<?php
$pdo = new POD('mysql:host=localhost;dbname=test', 'username', 'password', [PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8']);
$sth = $pdo->prepare("SELECT id, value FROM browsers");
$rows = $sth->execute()->fetchAll();
?>
<div>Choose a browser from this list:</div>
<input list="browsers" />
<datalist id="browsers">
<? foreach ($rows as $row): ?>
<option value="<?=$row['value']?>">
<? endforeach; ?>
</datalist>

Related

PHP-jquery-ajax dynamic dependent selection - difficulty

I'm programming a simple form with a dynamic dependent selection. There are two files. One is a php file with html, javascript and php inside, the second is a php file to get data for the second selection and send them back in json format. In the first (and main) file I have the form with two select fields. First field is for province, second is for towns. Data are in a MySQL db, two tables, table_provinces for provinces (103 rows) and table_towns for towns (8000 rows). Normally connect to the db as usual and also link to jquery using a javascript link. First I get provinces options for the first select field, using php to get the values from table_provinces of the db. Then with the javascript " on('change',function(){ here I use ajax...}) " I pass the selected value using ajax to a php file that might extract towns from table_towns and give back (in json format) values to populate the second select field. Javascript gets correctly the selected value from the first selection field (I used an alert to know it), but nothing more happens. So this is the code.
Link to jquery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
HTML first select field:
<form method="post" action="usemychoice.php">
<select id="province" name="province" color="white">
<option value="" selected>Select a province</option>
This is how I populate the first select field:
<?php
$sql = "SELECT * FROM table_provinces";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "<option value='".$row['prov']."'>".$row['extended_province']."</option>";
}
} else {
echo "Error: ..........";
}
?>
And after closing that field with a /select I have this code to get values for populating with town names the second select field:
<script type="text/javascript">
$(document).ready(function(){
$('#province').on('change',function(){
var provinceID = $(this).val();
if(provinceID){
window.alert("ok you've chosen the province "+provinceID);
$.ajax({
type:'POST',
url:'get_towns.php',
data: 'prov='+provinceID,
success:function(html){
$('#town').html(html);
}
});
}else{
$('#town').html('<option value="">Please select the province first</option>');
}
});
});
</script>
This is the get_town.php code:
<?php
//*****after a require to the connection db routine"
if(!empty($_POST["prov"])) {
$sql = "SELECT * FROM table_towns WHERE prov LIKE '%" .$_POST['prov']."%'";
$result = mysqli_query($conn, $sql);
$json = [];
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$json[$row['prov']] = $row['town'];
} else {
echo "Error: .................";
}
echo json_encode($json);
}
?>
Finally I have the html code :
<select id="town" name="town" color="white">
<option value="" selected>Select province first</option>
At the end of the day, the code has something wrong because I don't get any data back from get_town.php to populate the second select field, and since I didn't see a window.alert that I've put there to check ongoing execution (you don't see it in the code posted here), it seems that is not executed. Any help?
url:'get_towns.php',
Isn't it get_town.php without plural ?
Apparently it seems that the output of get_town.php is JSON
echo json_encode($json);
but in your JS it is directly output to an html element
$('#town').html(html);
Solution:
Either modify get_town.php to send html OR modify the success function in JS to convert received JSON to proper html.
I hope this will help.
UPDATE:
Replace this part of php
while($row = mysqli_fetch_assoc($result)) {
$json[$row['prov']] = $row['town'];
}
with something
echo '<option value="" selected>Select Town</option>';
while($row = mysqli_fetch_assoc($result)) {
echo '<option value="'.$row['town'].'" color="white">'.$row['town'].'</option>';
}
and finally remove the line
echo json_encode($json);

How to display data with radio buttons based on drop down selection?

I'm trying to dynamically generate radio buttons with data in front of them. The data that is to be displayed in front of the radio button is based on a drop down selection, which also displays some data in a text box using javascript.
I tried taking the selected option in a string and use it in the next query, but I know I am doing it wrong.
Database Connection
$db = pg_connect("");
$query = "select account_name,account_code,address1,address2,address3 FROM
customers";
$result = pg_query($db,$query);
//NEW QUERY
$sql1= "select name from conferences";
$result1= pg_query($db, $sql1);
//END
//New Code
<select class="form-control" id="conference" name="conference">
<option value="">Select Conference...</option>
<?php while($rows1 = pg_fetch_assoc($result1)) { ?>
<option value="<?= $rows1['code']; ?>"><?= $rows1['name']; ?></option>
<?php } ?>
</select>
<br>
// END OF NEW CODE
Dropdown to select the data.
<select onchange="ChooseContact(this)" class="form-control"
id="account_name" name="account_name" >
<?php
while($rows= pg_fetch_assoc($result)){
echo '<option value=" '.$rows['address1'].' '.$rows['address2'].'
'.$rows['address3'].''.$rows['account_code'].'">'.$rows['account_name'].'
'.$_POST[$rows['account_code']].'
</option>';
}?>
</select>
Displaying data in the text area based on the selcted value using javascript. (The code works fine till here)
<textarea readonly class="form-control" style="background-color: #F5F5F5;"
id="comment" rows="5" style="width:700px;"value=""placeholder="Address...">
</textarea>
<script>
function ChooseContact(data) {
document.getElementById ("comment").value = data.value;
}
</script>
Displaying data in front of the radio buttons based on the selected option(This code works if I use some random value in the query, but not if I use the selected value 'account_code' from the previous query. I'm using POST GET method to carry the selected value)
<?php
//NEW CODE
$sql = "select order_number, order_date from orders where
customer_account_code = '3000614' and conference_code='DS19-'"; <-Data
gets displayed when put random value like this.
$code = $_GET[$rows['account_code']];
$conf = $_GET[$rows1['conference_code']];
$sql = "select order_number, order_date from orders where
customer_account_code = '$code' and conference_code= '$conf']"; <- But I
want to display the data against the selected value, i.e, the 'account_code'
in the variable $code from the dropdown select
//END
$res = pg_query($db,$sql);
while($value = pg_fetch_assoc($res) ){
echo "<input type='radio' name='answer'
value='".$value['order_number']." ".$value['order_date']."'>"
.$value['order_number'].$value['order_date']." </input><br />";
}
?>
I need to help to find a way to put the selected 'account_code' in a variable and use it in the $sql query.
Please try with this code : (It's work for me)
1- Add this line to your HTML <head>:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript"></script>
2- Edit your CODE to this:
Dropdown to select the data:
<select class="form-control" id="account_name" name="account_name">
<option value=""></option>
<?php while($rows = pg_fetch_assoc($result)) { ?>
<option value="<?= $rows['address1'].' '.$rows['address2'].' '.$rows['address3'].'-'.$rows['account_code']; ?>"><?= $rows['account_name']; ?></option>
<? } ?>
</select>
Displaying data in the text area based on the selected value using jQuery:
<textarea readonly class="form-control" style="background-color: #F5F5F5;"
id="comment" rows="5" style="width:700px;" value="" placeholder="Address..."></textarea>
jQuery Code:
<script type="text/javascript">
$('#comment').val($('#account_name').val()); // MAKE A DEFAULT VALUE
(function($) {
$('#account_name').change(function() {
$('#results').html(''); // REMOVE THE OLD RESULTS
var option = $(this).val();
$('#comment').val(option);
// EDIT RADIO WITH AJAX
$.ajax({
type: "POST",
url: "path/test.php",
dataType:'JSON',
data: $('#account_name').serialize()
}).done(function(data) {
for (var i = 0; i < data.length; i++) {
// ADD RADIO TO DIV RESULTS
$('#results').append('<input type="radio" name="answer" value="'+data[i].order_number+'">'+data[i].order_date+'</input><br>');
}
});
});
})(jQuery);
</script>
after that, add this HTML to your page, to show RESULTS FROM AJAX DATA
<!-- RADIOs -->
<div id="results"></div>
3- Create a new file like path/test.php
in this file, use this CODE to return values with JSON :)
<?php
header('Content-type: application/json');
// CONNECT (JUST USE YOUR CUSTOM CONNECTION METHOD & REQUIRE CONFIG FILE IF YOU WANT)
$db = pg_connect("");
$value = explode('-', $_POST['account_name']);
// EXPLODE AND GET LAST NUMBER AFTER < - >
$code = (int) end($value);
$sql = "select order_number, order_date from orders where customer_account_code = '$code'";
$res = pg_query($db, $sql);
// CREATE JSON RESULTS
$is = '';
while($data = pg_fetch_assoc($res)) {
$is .= json_encode($data).', ';
}
// AND GET ALL
echo '['.substr($is, 0, -2).']';
?>

get the result for third dropdown by passing the selected dropdown values

I am showing the dropdowns based on the above selected dropdowns. I want the result in third dropdown. For that I am writing the sql query in php and writing the change event in jquery but i am unable to get the result. I am stuck up there
My jquery looks like
$(document).ready(function(){
$("#parent_cat,#city").change(function(){
$.get('loadlocation.php?city=' + $(this).val() , function(data) {
$("#sub_cat").html(data);
});
});
});
parent_cat and city are from selected values
<label for="category">Category</label>
<select name="parent_cat" id="parent_cat">
<?php while($row = mysql_fetch_array($query_parent)): ?>
<option value="<?php echo $row['name']; ?>"><?php echo $row['name']; ?></option>
<?php endwhile; ?>
</select>
<br/><br/>
<label for="city">city</label>
<select name="city" id="city">
<?php while($row = mysql_fetch_array($query_parent1)): ?>
<option value="<?php echo $row['city']; ?>"><?php echo $row['city']; ?></option>
<?php endwhile; ?>
</select>
<br/><br/>
And my php file loadlocation.php is
<?php
include('config.php');
$parent_cat = $_GET['parent_cat'];
$city = $_GET['city'];
$query = mysql_query("SELECT table_place_detail.post_title FROM table_terms, table_place_detail, table_post_locations
WHERE table_place_detail.post_location_id = table_post_locations.location_id AND table_place_detail.default_category = table_terms.term_id AND table_post_locations.city = '$city' AND table_terms.name = '$parent_cat'");
while($row = mysql_fetch_array($query)) {
echo "<option value='$row[post_title]'>$row[post_title]</option>";
}
?>
I want to fetch the values of parent_cat, city to loadlocation.php but i am not able to get those values. I want to load the two values and get the query excecuted and the values should shown in 3rd dropdown as below can any one help this issue
<label>Vendors List 1</label>
<select name="sub_cat" id="sub_cat"></select>
Two things stand out
You send only one value, ?city=
According to the manual jQuery.get(), you can send additional parameters as a plain object. This means, you don't need to build a query string, but can pass parent_cat and city separately, e.g.
$.get("loadlocation.php",
{ parent_cat: $('#parent_cat').val(), city: $('#city').val() },
function(data) {
$('#sub_cat').html(data);
});
And finally, the mandatory hint at each mysql_* page
Warning This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
mysqli_query()
PDO::query()

PHP Dynamic ComboBox

i almost got this, but i need the comboboxes to be dynamic and i cant get it, this is how it looks:
! http://imgur.com/ppoKOBI
I have this code:
<form action="PostDelPhoto.php" name="delForm" method="post" >
<select name="categoriaMod" id="catMod">
</br>
<?php
require('bd.php');
$sql="SELECT * FROM Categorias ORDER BY ID DESC;";
$queryexec=mysql_query($sql,$conn);
while ($row = mysql_fetch_array($queryexec)){
$Categoria =$row["nombre_categoria"];
echo '<option value="'.$Categoria.'">'.$Categoria.'</option>';
};
echo'</select>';
?>
<select name="SelectPhoto" id="SelectPhoto" value="">
<?php
require('bd.php');
$sql="SELECT * FROM Paisajes ORDER BY ID DESC;";
$queryexec=mysql_query($sql,$conn);
while ($row = mysql_fetch_array($queryexec)){
$filename =$row["nombre_archivo"];
echo '<option value="'.$filename.'">'.$filename.'</option>';
};
echo'</select>';
?>
In this last php While, I need static "Paisajes" from the SQL Query, to take the value in real time from option combobox after it, but i cant manage to get it.
All ideas are welcome! Thanks!

Getting form data from both dependent drop down lists to php

I have a form on my page which includes 2 dependent drop down lists. When user selects value from 1st list, it populates the second list and user then selects value from 2nd list.
I want to submit form data to php page to insert into table in mysql, but when it submits, all data is passed EXCEPT value from 2nd list. Value from 1st list and other input fields are passed OK.
I've tried everything I know and I can't make this work. Any ideas how to implement this?
This is the form from index2.php (EDIT: simplified the form element):
<form name="part_add" method="post" action="../includes/insertpart.php" id="part_add">
<label for="parts">Choose part</label>
<select name="part_cat" id="part_cat">
<?php while($row = mysqli_fetch_array($query_parts)):?>
<option value="<?php echo $row['part_id'];?>">
<?php echo $row['part_name'];?>
</option>
<?php endwhile;?>
</select>
<br/>
<label>P/N</label>
<select name="pn_cat" id="pn_cat"></select>
<br/>
<input type="text" id="manufactured" name="manufactured" value="" placeholder="Manufactured" />
<input id="submit_data" type="submit" name="submit_data" value="Submit" />
</form>
And this is javascript:
$(document).ready(function() {
$("#part_cat").change(function() {
$(this).after('<div id="loader"><img src="img/loading.gif" alt="loading part number" /></div>');
$.get('../includes/loadpn.php?part_cat=' + $(this).val(), function(data) {
$("#pn_cat").html(data);
$('#loader').slideUp(200, function() {
$(this).remove();
});
});
});
});
And this is php to load 2nd list:
<?php
include('db_connect.php');
// connects to db
$con=mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$part_cat = $_GET['part_cat'];
$query = mysqli_query($con, "SELECT * FROM pn WHERE pn_categoryID = {$part_cat}");
while($row = mysqli_fetch_array($query)) {
echo "<option value='$row[part_id]'>$row[pn_name]</option>";
}
?>
I am getting $part_cat from 1st list to insertpart.php, but $pn_cat.
EDIT: this is insertpart.php (simplified and it just echos resuls)
<?php
//Start session
session_start();
//Include database connection details
require_once('../includes/db_details.php');
//DB connect
$con=mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
// find part name based on ID
$part_typeID = mysqli_real_escape_string($con, $_POST['part_cat']);
$part_name_result = mysqli_query($con, "SELECT part_name FROM parts WHERE part_id = $part_typeID");
$part_row = mysqli_fetch_array($part_name_result, MYSQL_NUM);
$part_type = $part_row[0];
echo"part_type='$part_type'";
//find pn value based on id
$pn_typeID = mysqli_real_escape_string($con, $_GET['pn_cat']);
$pn_name_result = mysqli_query($con, "SELECT pn_name FROM pn WHERE pn_id = $pn_typeID");
$pn_row = mysqli_fetch_array($pn_name_result, MYSQL_NUM);
$pn = $pn_row[0];
echo"pn='$pn'";
mysqli_close($con);
?>
It's still work in progress, so the code is ugly, and I know I'm mixing POST and GET that is being rectified. If I echo $pn_cat on this page there is no output, $part_type is OK.
Can you try swapping the $_GET in
$pn_typeID = mysqli_real_escape_string($con, $_GET['pn_cat']);
with $_POST?
$pn_typeID = mysqli_real_escape_string($con, $_POST['pn_cat']);
EDIT: based on asker's feedback and idea for a work-around
NOTE: This edit is based on what you suggested, even though I tested your original code and received satisfactory results (after I removed the PHP and MySQL from the code and replaced them with suitable alternatives).
The Work-Around
Here's the HTML for the hidden field:
<input type="hidden" id="test" name="test" value="" placeholder="test" />
Here's a simple Javascript function:
function setHiddenTextFieldValue(initiator, target){
$(initiator).change(function() {
$(target).val($(this).val());
});
}
You can call the above function within the function(data) { of your original code with something like:
setHiddenTextFieldValue('#pn_cat', '#test'); // note the hashes (#)
I also recommend you to hard-code the following HTML into your HTML and PHP files, right before the looping of the <option>s begin:
<option value="" disabled selected="selected">Select</option>
The above line could improve user experience, depending on how you want your code to work. Note however, that this is entirely optional.
Solved it! It was just a stupid typo, can't believe I've lost 2 days over this!
In loadpn.php instead of:
$row[part_id]
it should read:
$row[pn_id]
For some reason drop down worked, but offcourse value of pn_cat wasn't being set.
Also this works in setting 2 field values (which now I don't need but if somebody wants to know):
$(document).ready(function() {
$("#part_cat").change(function() {
$('#pn_hidden').val($(this).val());
});
$("#pn_cat").change(function() {
$('#pn_hidden2').val($(this).val());
});
});
Also changed js to post:
$(document).ready(function() {
$("#part_cat").change(function() {
$.post('../includes/loadpn.php', 'part_cat=' + $(this).val(), function(data) {
$("#pn_cat").html(data);
});
});
});
And thanks for the:
<option value="" disabled selected="selected">Select</option>
It really helps with user experience.

Categories

Resources