I've been working on this for a couple of hours and it should work but i'm missing something!
basically, i'm using jquery autocomplete with json source, with 2 values id and description.
Description should show up in suggestions and if item is selected and ID passed to a hidden field ( the field is not hidden currently for testing purposes)
here's my code:
$(function() {
$("#CurrentProv").autocomplete({
source: "inc/provider_term.php",
minLength: 3,
formatItem: function(data, i, n, value) {
return value.split("|")[1];
}
});
$("#CurrentProv").result(function(event, data, formatted) {
if (data)
$("input#fid").val(data[0]);
});
});
//PHP valid json output
$term = $_GET['term'];
$sql = "SELECT * FROM db.table WHERE PName LIKE '%$term%'";
$res = mysql_query($sql, $conn) or die(mysql_error());
while ($row = mysql_fetch_array($res)) {
$searchArray['value'] = $row['PID'].'|'.$row['PName'];
$search[] = $searchArray;
}
echo json_encode($search);
I've searched and done various variations and still doesn't work!!! My brain is shutting down!!!!!!!!
First, switch to using the actual jQuery UI autocomplete.
You'll have to sort out how to format your items on the server side, or in your JSON callback, because formatItems is not supported anymore. Check out this guide for some help.
Now that you've done that, here's how it will look:
$(function() {
$("#CurrentProv").autocomplete({
source: "inc/provider_term.php", //or you can use a callback here
minLength: 3,
change: function(event, ui) {
$("input#fid").val(ui.item.value);//or ui.item.desc perhaps
}
});
});
Working tweaked PHP code and JS as Ryley suggested:
$term = $_GET['term'];
$sql = "SELECT * FROM db.table WHERE PName LIKE '%$term%'";
$res = mysql_query($sql, $conn) or die(mysql_error());
while ($row = mysql_fetch_array($res)) {
$searchArray['value'] = $row['PID'];
$searchArray['id'] = $row['PName'];
$search[] = $searchArray;
}
echo json_encode($search);
$(function() {
$("#CurrentProv").autocomplete({
source: "inc/provider_term.php", //or you can use a callback here
minLength: 3,
change: function(event, ui) {
$("input#fid").val(ui.item.id);//or ui.item.desc perhaps
}
});
Related
How can I add clickable link to json_encode?
I did a multiple query auto complete textbox with jquery. Maybe that's not the correct way how to do multiple queries but that's works anyway.
$conn = new PDO("mysql:host=".DB_SERVER.";port=3306;dbname=".DB_NAME, DB_USER, DB_PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT * FROM azonositok WHERE guid LIKE :term');
$stmt->execute(array('term' => '%'.$_GET['term'].'%'));
while($row = $stmt->fetch()) {
$return_arr[] = $row['guid']; /// I want to link to http://example.com/guid.php
}
$stmt1 = $conn->prepare('SELECT * FROM felhasznalok WHERE fnev LIKE :term');
$stmt1->execute(array('term' => '%'.$_GET['term'].'%'));
while($row1 = $stmt1->fetch()) {
$return_arr[] = $row1['fnev']; /// I want to link to http://example.com/profile.php
}
} catch(PDOException $e) {
echo 'HIBA: ' . $e->getMessage();
}
echo json_encode($return_arr);
}
You'll have to add a function to execute on selection of an item in the autocomplete widget's dropdown list.
This is done with the select property as follows:
$(".auto").autocomplete({
source: "search.php",
minLength: 1,
select: function(event, ui) {
window.location.href = ui.item.value;
}
});
This changes the current window's location to the selected item's value.
EDIT:
To change the default behavior where the value is displayed on focus/select to display the label instead, you could try:
$(".auto").autocomplete({
source: "search.php",
minLength: 1,
select: function(event, ui) {
event.preventDefault();
$('.auto').val(ui.item.label);
window.location.href = ui.item.value;
},
focus: function(event, ui) {
event.preventDefault();
$('.auto').val(ui.item.label);
}
});
I want to make a dropdown list which is dependable on another dropdown list. Both dropdown list's values are retrieved from database. How can i do that?please help .
Also how can i pass the category name to database mysql query page (list.php).
I currently have this which list all subcategories..but i want to list only particular subcategory depending on category
<script>
$(document).ready(function(){
$.getJSON("getlist.php", function(return_data){
return_data.forEach(function(e,i){
$('#catn').append('<option value= "'+e.catname+'">'+e.catname+'</option>');
});
});
});
$(document).ready(function(){
$.getJSON("list2.php",{'catname':catname},function(return_data){
return_data.forEach(function(h,i){
$('#scatn').append('<option value= "'+h.subcatname+'">'+h.subcatname+'</option>');
});
});
});
list.php
<?php
$catname=$_GET['catname'];
$conn =mysqli_connect("localhost", "root", "", "project");
$sql = "SELECT * FROM catd where catname='$catname'";
$result = mysqli_query($conn, $sql);
$scat_arr = array();
while( $row = mysqli_fetch_array($result) )
{
$catid = $row['cid'];
$catname = $row['catname'];
$scat_arr[] = array("cid" => $catid, "catname" => $catname);
}
echo json_encode($scat_arr);
?>
You can use .change function in JS. While the first dropdown is changing it triggers the ajax with POST method to post to your file list.php(where your query runs).
jQuery(document).ready(function() {
$('#catname').change(function(){
var catname = $(this).val();
$.ajax({
url:list.php,
method:"POST",
data:{
catname:catname
},
dataType:"json",
success:function(data){
var $el = $("#subcatname");
$el.empty();
$el.append($("<option></option>")
.attr("value", '')
.attr("hidden",'')
.text('Select Sub Cat Name'));
$.each(data, function(index, value){
$el.append('<option
value="'+value.catid+'">'+value.catname+'</option>')
});
});
You must echo json_encode the output so that ajax recognize the returned value. And then you can append the values by casting it using append.
Hopes this helped.
I have a autocomplete function that works fine but where I want to extend the drop down details a bit. It looks like this:
Datafile (form-lookup.php):
if ($db)
{
$fetch = mysqli_query($db,"SELECT * FROM uni_labels where label_name like '%" . $_GET['term'] . "%'");
/* Retrieve and store in array the results of the query.*/
while ($row = mysqli_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['label'] = htmlspecialchars_decode($row['label_name']);
$row_array['lookupid'] = $row['id'];
$row_array['address'] = $row['label_address'];
$row_array['number'] = $row['label_number'];
$row_array['postalcode'] = $row['label_postalCode'];
$row_array['country'] = $row['label_country'];
array_push($return_arr,$row_array);
}
}
/* Free connection resources. */
mysqli_close($db);
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
My page that retreives the data looks like this:
$(function() {
$("#step1Name").autocomplete({
source: "/pages/form-lookup.php?country=dk",
minLength: 2,
select: function(event, ui)
{
$('#step1Name').val(ui.item.address);
$('#lookupid').val(ui.item.lookupid);
$('#vej').val(ui.item.address);
}
});
});
<input maxlength="100" type="text" required="required" class="form-control input-lg" name="step1Name" id="step1Name" />
Everyting works just great, but I would like for my drop down to show both $row_array['label'] and $row_array['address'], and when I select a value in the drop down, the input box will only output the $row_array['label'] value.
In the datafile I have tried to add the address to the label, like this:
$row_array['label'] = htmlspecialchars_decode($row['label_name'])." - ".$row['label_address'];
This displays the value fine in the drop down, but when selecting the choice, the input box of course contains too much data, where I only want it to display the label_name.
Can someone point me in the right direction?
Thanks in advance.
Add this to your autocomplete code:
select: function(event, ui) {
event.preventDefault();
var name = ui.item.value.split('-')[0];
$("#starter").val(name);
},
focus: function(event, ui) {
return false;
}
So your updated autocomplete code will be like that:
$("#step1Name").autocomplete({
source: "/pages/form-lookup.php?country=dk",
minLength: 2,
select: function(event, ui) {
event.preventDefault();
var name = ui.item.value.split('-')[0];
$("#starter").val(name);
return false;
},
focus: function(event, ui) {
return false;
}
});
I have a html search bar like so:
<form id="testblah" action="search_results.php" method="GET">
<input type="text" name="search" class="Search_bar_box" id="search">
</form>
I am then using Jquery to auto complete the input of a search criteria using pre-defined tags like so:
<script>
$(function() {
$('form').each(function() {
$(this).find('input').keypress(function(e) {
// Enter pressed?
if(e.which == 10 || e.which == 13) {
this.form.submit();
}
});
});
});
$(function () {
var availableTags = [
"Telehandlers",
"Cranes",
"Fork Attachments",
"Aggreko",
"12 Tonne Telhandlers",
"Marwood",
"Crane Suppliers in Manchester",
"Total",
"Oil, Gas & Lubricants",
"Tomato Plant"
];
$("#search").autocomplete({
source: availableTags,
select: function (event, ui) {
window.location = 'search_results.php?search=' + ui.item.value;
}
});
$('#searchForm').on("submit", function (event) {
event.preventDefault();
alert($('#search').val());
});
});
</script>
This all works fine, however, what I want to do now is change my tags from pre-defined text so that my tags are instead pulled from my MySQL data. so I am trying to run a MySQL query to get all data from my table like so:
<?php $query12 = "SELECT * FROM supplier_users, supplier_stats GROUP BY supplier_users.user_id";
$result12 = mysql_query($query12);
while($row1 = mysql_fetch_assoc($result12)) {
$tags = $row1; } ?>
and then trying to place my string inside the jquery tags section like so:
$(function () {
var data = "<?= $tags ?>";
var availableTags = [
data ];
however this stops my jquery from working. Can someone please show me where I am going wrong and how I would need to do this. thanks in advance
You can edit your php code like the following,
<?php
$query12 = "SELECT * FROM supplier_users, supplier_stats GROUP BY supplier_users.user_id";
$result12 = mysql_query($query12);
$tags = array();
while($row1 = mysql_fetch_assoc($result12)) {
array_push($tags, $row1);
}
?>
and in java script as Naruto told replace the
var data = "<?= $tags ?>";
with the following
var data = "<?php echo json_encode($tags); ?>";
// array
var availableTags = JSON.parse(data);
Try to use this kind of solution.
The following php block searches and returns names and i want to select an item and at ajax be able to get other items in the row selected beside "name". How do i separate them with ajax?
<?php
require_once '../php/db_conx.php';
$req = "SELECT name "
."FROM profiles "
."WHERE name LIKE '%".$_REQUEST['term']."%' ";
$query = mysql_query($req);
while($row = mysql_fetch_array($query))
{
$results[] = array('label' => $row['name']);
}
echo json_encode($results);
?>
Here's ajax.
$(function() {
$( "#SearchInput").autocomplete({
source: 'Search.php',
minLength: 1,
select: function(event, ui) {
$('#Name').append(ui.item.label);
}
});
});
You can use _renderItem method
_renderItem: function( ul, item ) {
$( "#selector" ).text( item.name );// let name is in json
}
Or you can get the name in select event also like,
select: function(event, ui) {
$('#Name').append(ui.item.label);
$( "#selector" ).text( item.name );// let name is in json
}
Try this:
I think you need to parse data from array.
var contact = JSON.parse(jsontext);
document.write(contact.surname + ", " + contact.firstname);
Use the variable name you have used.
Read More on: http://msdn.microsoft.com/en-us/library/ie/cc836466(v=vs.94).aspx
Thanks