jquery autocomplete with php source & json issue - php

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);
?>

Related

jQuery Autocomplete ComboBox Options Echo'd by PHP Getting Removed when Match Typed

Currently I have a combobox which options gets echo'd by PHP since the values are in an array. The code of the combobox is as follows:
<div class="ui-widget">
Project
<br>
<select id="combobox">
<?php
foreach($projects as $value)
{
echo "<option value=".$value.">".$value."</option>";
}
?>
</select>
</div>
What I am trying to achieve is when a user types into the combobox he gets a dropdown-list with all the entries of the array that match the text the user typed in the combobox.
The user can then select an option from the dropdown-list or choose to type the entry completely(but it needs to mach the entries in the dropdown-list).
To achieve all this i am currently using the Autocomplete function of jQuery.
All the code that I am using to achieve this can be watched here: http://jqueryui.com/autocomplete/#combobox.
The code for the combobox I use is as follows:
<script>
(function( $ ) {
$.widget( "custom.combobox", {
_create: function() {
this.wrapper = $( "<span>" )
.addClass( "custom-combobox" )
.insertAfter( this.element );
this.element.hide();
this._createAutocomplete();
this._createShowAllButton();
},
_createAutocomplete: function() {
var selected = this.element.children( ":selected" ),
value = selected.val() ? selected.text() : "";
this.input = $( "<input>" )
.appendTo( this.wrapper )
.val( value )
.attr( "title", "" )
.addClass( "custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left" )
.autocomplete({
delay: 0,
minLength: 0,
source: $.proxy( this, "_source" )
})
.tooltip({
tooltipClass: "ui-state-highlight"
});
this._on( this.input, {
autocompleteselect: function( event, ui ) {
ui.item.option.selected = true;
this._trigger( "select", event, {
item: ui.item.option
});
},
autocompletechange: "_removeIfInvalid"
});
},
_createShowAllButton: function() {
var input = this.input,
wasOpen = false;
$( "<a>" )
.attr( "tabIndex", -1 )
.attr( "title", "Show All Items" )
.tooltip()
.appendTo( this.wrapper )
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass( "ui-corner-all" )
.addClass( "custom-combobox-toggle ui-corner-right" )
.mousedown(function() {
wasOpen = input.autocomplete( "widget" ).is( ":visible" );
})
.click(function() {
input.focus();
// Close if already visible
if ( wasOpen ) {
return;
}
// Pass empty string as value to search for, displaying all results
input.autocomplete( "search", "" );
});
},
_source: function( request, response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
response( this.element.children( "option" ).map(function() {
var text = $( this ).text();
if ( this.value && ( !request.term || matcher.test(text) ) )
return {
label: text,
value: text,
option: this
};
}) );
},
_removeIfInvalid: function( event, ui ) {
// Selected an item, nothing to do
if ( ui.item ) {
return;
}
// Search for a match (case-insensitive)
var value = this.input.val(),
valueLowerCase = value.toLowerCase(),
valid = false;
this.element.children( "option" ).each(function() {
if ( $( this ).text().toLowerCase() === valueLowerCase ) {
this.selected = valid = true;
return false;
}
});
// Found a match, nothing to do
if ( valid ) {
return;
}
// Remove invalid value
this.input
.val( "" )
.attr( "title", value + " didn't match any item" )
.tooltip( "open" );
this.element.val( "" );
this._delay(function() {
this.input.tooltip( "close" ).attr( "title", "" );
}, 2500 );
this.input.autocomplete( "instance" ).term = "";
},
_destroy: function() {
this.wrapper.remove();
this.element.show();
}
});
})( jQuery );
$(function() {
$( "#combobox" ).combobox();
$( "#toggle" ).click(function() {
$( "#combobox" ).toggle();
});
});
</script>
The problem that I am having right now is when a user types text in the combobox and the dropdown-list appears and he fully types out an entry of the dropdown-list the combobox still gets cleared. This is not supposed to happen. Whenever the user clicks on the combobox the item doesn't get cleared.
To make is a bit clearer here is an image of the combobox:
So above you can see the combobox. Whenever a user types something he gets a dropdown-list with all the results matched(project 1, project 10).
The problem that I am having right now is when a user types out "project 1" without clicking on the item in the dropdown-list the text in the combobox still gets removed by the Autocomplete function in jQuery.
If the user clicks on the item then there is no problem at all.
Funny thing is that the Autocomplete function works without any problems if I don't echo the option elements with PHP.
so:
<option value="project 1">project 1</option>
<option value="project 2">project 2</option>
<option value="project 3">project 3</option>
instead of:
foreach($projects as $value)
{
echo "<option value=".$value.">".$value."</option>";
}
Any help is greatly appreciated.
Change from
echo "<option value=".$value.">".$value."</option>";
TO
echo "<option value='".$value."'>".$value."</option>";

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;
}
}

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() {
.................
});
}

JQuery UI Autocomplete with PHP file source

I am trying to use JQueryUI autocomplete, with data coming from a remote source (another php script).
Below is the example given in the demos on the JQueryUI website:
<style>
.ui-autocomplete-loading { background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat; }
</style>
<script>
$(function() {
function log( message ) {
$( "<div/>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}
$( "#birds" ).autocomplete({
source: "search.php",
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
});
</script>
My question is about the PHP script "search.php". Should this script simply return an array?
The response should be a JSON formatted array in either of these two formats:
An Array of Strings:
[ "Choice1", "Choice2" ]
OR
An Array of Objects with label and value properties:
[ { label: "Choice1", value: "value1" }, ... ]

Jquery UI autocomplete link to item

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.

Categories