Jquery UI autocomplete link to item - php

I want to make a search box, where you can search between records in the database.
search.php looks like this:
<?php
// connect to mysql
require_once('includes/connect.php');
// include config
include('includes/config.php');
$nameser = $_GET['term'];
$names = array();
$result = mysql_query("SELECT name,customerid FROM customers WHERE name LIKE '%".$nameser."%' ORDER BY name ASC");
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['id'] = $row['customerid'];
$row_array['value'] = htmlentities($row['name']);
array_push($names,$row_array);
}
echo json_encode($names);
?>
Javascript part looks like this:
$("#tags").autocomplete({
source: "search.php",
minLength: 2,
select: function(event, ui) {
window.location = ("customers.php?action=view&cid=" + item.id)
//$('#tags').val(ui.item.id);
//return false;
}
})
.data("autocomplete")._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a href='customers.php?action=view&cid="+ item.id + "'>"+ item.label + "</a>" )
.appendTo( ul );
};
However, this gives the error:
ReferenceError: item is not defined
What I want to happen is, that when I click something in the result list, I get redirected to the url
customers.php?action=view&cid={CustomerID}
Anyone got an idea?
EDIT:
Correct Javascript code that works:
$("#tags").autocomplete({
source: "search.php",
minLength: 2,
select: function(event, ui) {
window.location = ("customers.php?action=view&cid=" + ui.item.id)
//$('#tags').val(ui.item.id);
//return false;
}
})
.data("autocomplete")._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a href='customers.php?action=view&cid="+ item.id + "'>"+ item.label + "</a>" )
.appendTo( ul );
};

i have a demo with a working example in jsfiddle. you can see it here:
the key is to get a valid url value in the autoselect select method. be sure to console.log the ui value so you can see what is available for you to use. i was able to use the standard ui.item.value value to send the user to another page.
to test my demo:
1.) go into the input box and enter "a".
2.) select "http://www.utexas.edu"
3.) the new page will load.

Related

jQuery Autosuggest with mySQL and PHP

I'm setting up an autosuggest where a person can enter a state and get referred to a page on my website. I am linking this to a database because once I get this simple example working I will have 50,000 places in a database to look up. Right now I just have states.
Everything works good except that when a user selects a state from the list, the name filled out in the box is the url link that I am sending them too rather than the correct label. (But I am still going to send them to a url.) Its a small point but it just doesn't look right. Any ideas?
jQuery(document).ready(function($){
$('#searchbox').autocomplete({
source:'suggest.php',
minLength:1,
select: function(event, ui) {
$( "#searchbox" ).val( ui.item.label );
var url = ui.item.value;
if(url != '#') {
window.location.href = url;
}
},
html: true,
open: function(event, ui) {
$(".ui-autocomplete").css("z-index", 1000);
}
});
});
The php returns both the web link and the label being searched:
while( $row = mysql_fetch_array($rs, MYSQL_ASSOC) )
{
$data[] = array(
'label' => $row['Label'],
'value' => $row['Link']
);
}
Here is the example running 1
It looks like the select method's default behaviour is to set the textbox to use value instead of label. So using $( "#searchbox" ).val( ui.item.label ); won't work, regardless of the string you put in there. In that case, we should stop the default behaviour.
Putting event.preventDefault() in the select function seems to fix the problem.
select: function(event, ui) {
event.preventDefault();
$( "#searchbox" ).val( ui.item.label );
var url = ui.item.value;
if(url != '#') {
window.location.href = url;
}
}

Separate json encoded array result

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

Multiple jQuery autocomplete in one page

UPDATE
I checked the dropdown elements and it seems that the succeeding dropdown elements are not populated by the
.data( 'ui-autocomplete' )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append(
'<a class="select-group"><span class="mini-headtitle">' + item.institution_name +
'</span><br/><span class="mini-subtitle">' + item.municipality + '</span></a>' )
.appendTo( ul );
};
}
part. But the "missing" elements still has the items needed! How do I solve this?
PROBLEM
I have dynamically added textboxes which correspond to a jQuery Autocomplete script.
Whenever a new textbox is added to the DOM, it should also have the same autocomplete from the first.
Autocomplete works on all newly added DOM textboxes but only the first instance has its select box filled with options.
First textbox
Succeeding textboxes
My textboxes have the id InstitutionName[1] where the number grows as more elements are added.
I use the code below:
function ajax_connect_to_db()
{
$('input[id^="InstitutionName"]')
.autocomplete({
minLength: 0,
source: "new_account/get_institution_info_db",
dataType: "json",
focus: function( event, ui ) {
$( this ).val( ui.item.institution_name );
return false;
},
select: function( event, ui ) {
// get unique textbox number inside brackets
var str = $(this).attr('id');
var pos = str.indexOf("[") + 1;
var index = str.slice(pos, str.lastIndexOf("]"));
// fill in the respective textboxes
$(this).val( ui.item.institution_name );
$( 'input[id="InstitutionID['+ index +']"]' ).val( ui.item.id );
$( 'input[id="InstitutionMunicipality['+ index +']"]' ).val( ui.item.municipality );
$( 'input[id="InstitutionProvince['+ index +']"]' ).val( ui.item.province );
return false;
}
})
.data( 'ui-autocomplete' )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append(
'<a class="select-group"><span class="mini-headtitle">' + item.institution_name +
'</span><br/><span class="mini-subtitle">' + item.municipality + '</span></a>' )
.appendTo( ul );
};
}
// target newly added DOM textboxes
setInterval( ajax_connect_to_db, 100 );
How do I make the select box show its content on all dynamically added elements?
try this
function ajax_connect_to_db()
{
$(function() {
.................
});
}

how to pass hidden id using json in jquery ui autocomplete?

perhaps it is duplicate,but i can't found solution so i posted this question.I am use jquery ui for auto complete search box. it works fine but the problem is i want to search using id.example:when user type paris,i try to send city_id in mysql for search. so problem is how to pass hidden id with json?
here the code:
<input type="text" name="grno" id="grno" class="input" title="<?php echo $lng['vldgrno'];?>
jquery code:
<script>
$(function() {
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$( "#grno" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "ui-autocomplete" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
source: function( request, response ) {
$.getJSON( "pages/search.php", {
term: extractLast( request.term )
}, response );
},
search: function() {
// custom minLength
var term = extractLast( this.value );
if ( term.length < 1 ) {
return false;
}
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( "," );
alert(data.id);
return false;
}
});
});
</script>
autocomplete.php :
<?php
mysql_connect('localhost','root','');
mysql_select_db('school');
$return_arr = array();
$term = trim(strip_tags($_GET['term']));//retrieve the search term that autocomplete sends
//create select query
$query = "select `grno`,`first_name`,`student_id` from `tbl_student` where `grno` like '%".$term."%' or `first_name` like '%".$term."%'";
// Run the query
$result = mysql_query ($query);
$array = array();
while($obj = mysql_fetch_array($result)){
$array['name'] = $obj['first_name']."(".$obj['grno'].")";
array_push($return_arr,$obj['first_name']."(".$obj['grno'].")");
}
$json = json_encode($return_arr);
echo $json;
?>
so.how to pass student_id in autocomplete.php,like label and value.{label='xyz' value='1'}
In autocomplete.php replace this code
array_push($return_arr,array("value"=>$obj['student_id'],"label"=>$obj['first_name']."(".$obj['grno'].")"));
and in your script change this
terms.push( ui.item.label );
$( "#stud_id" ).val( ui.item.value );
hope,this is what you find.

jquery autocomplete with php source & json issue

I want to create jquery autocomplete and php, the problem is the data shown in each record of the autocomplete has two values, I managed to do this like this (without PHP),
$(function() {
var authors = [
{
label: "jQuery",
desc: "the write less, do more, JavaScript library"
},
{
label: "jQuery UI",
desc: "the official user interface library for jQuery"
},
{
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine"
}
];
$( "#authorname" ).autocomplete({
minLength: 0,
source: authors,
focus: function( event, ui ) {
$( "#authorname" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#authorname" ).val( ui.item.label );
return false;
}
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
.appendTo( ul );
};
});
now I want to change the source to php page (change authors to "getauthors.php")
I don't know what to put inside "getauthors.php" in order to pass two things for label and desc.
I managed to pass one thing like this using json,
<?php
$json = array();
$json[]="test";
$json[]="test2";
$json[]="test3";
echo json_encode($json);
?>
which outputs like this,
you can see that the second thing is always undefined, how I can pass value to this in php using json (or any other way).
Thanks.
<?php
$json = array();
$json[] = array ("label"=>"test", "desc"=>"description");
...
echo json_encode($json);
?>

Categories