JQuery UI Autocomplete with PHP file source - php

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" }, ... ]

Related

Jquery Autocomplete error after load php in div : Uncaught "TypeError: Cannot read property 'label' of undefined "

My auto-complete getting error after loading php from selected item.
I want to create autocomplete and then load php file based on the selection, but after page is loaded, and typed some string again, got some result but. even just hover it it or select the item it gives error, shown from my chrome console.
I also tried change _renderItemData to _renderItem , but no difference.
$('#mainsearch').autocomplete({
minLength: 0,
source: studentArray,
focus: function( event, ui ) {
$( "#mainsearch" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#mainsearch" ).val( ui.item.label );
$( "#mainsearch-id" ).val( ui.item.value );
$( "#mainsearch-description" ).html( ui.item.label );
$( "#mainsearch-icon" ).attr( "src", "images/" + ui.item.icon );
showitem(ui.item.label);
return false;
}
}).data( "ui-autocomplete" )._renderItemData = function( ul, item ) {
return $( "<li>" )
.data( "ui-autocomplete-item", item )
.append( "MY CUSTOM STYLE" )
.appendTo(ul);
}; // END OF AUTOCOMPLETE
and my load page code:
function showitem(selectedentity){
$("#resultbox").html(" <div id='closeresult' name='closeresult' >X </div>" +
"<div ><h1>"+
selectedentity+
"</h1></div> ");
$("#resultbox").load('browseFrame.php');
}; // END OF showitem().
The errors :
Uncaught TypeError: Cannot read property 'label' of undefined search2.php:124
$.autocomplete.focus search2.php:124
$.Widget._trigger 12437:785
_on.menufocus 12437:6849
handlerProxy 12437:702
jQuery.event.dispatch 12436:3074
elemData.handle 12436:2750
jQuery.event.trigger 12436:2986
(anonymous function) 12436:3677
jQuery.extend.each 12436:648
jQuery.fn.jQuery.each 12436:270
jQuery.fn.extend.trigger 12436:3676
$.Widget._trigger 12437:783
$.widget.focus 12437:11795
(anonymous function) 12437:401
_on.mouseenter .ui-menu-item 12437:11505
handlerProxy 12437:702
jQuery.event.special.(anonymous function).handle 12436:3431
jQuery.event.dispatch 36:3074
elemData.handle
UPDATE :
Tried remove ALL javascript declaration as below from my loaded php file and everthing just fine :
<link rel="stylesheet" href="js/jquery-ui.css">
<script type="text/javascript" src="js/jquery-2.0.2.js"></script>
<script type="text/javascript" src="js/jquery-2.0.2.min.js"></script>
<script type="text/javascript" src="js/jquery-1.9.1.js"></script>
<script src="js/jquery.ui.core.js"></script>
<script src="js/jquery-ui.js"></script>
Can't explain why, but now my autocomplete works good and no more errors.
Sorry for my english...
JQuery(or any JS lib) needs to be loaded before you use can use it otherwise it will be threated as without jQuery... Load jQuery/jQuery UI in the head instead and you will be fine.

AutoComplete Highligh Issue

I want to highlight matched characters in jquery autocomplete.
If i type GC,it give me below,which is OK
Green Community
Now i want G and C both to be bold/strong.
$('#9').autocomplete({
source: "auto_loc_name.php",
selectFirst: true,
minLength: 0,
select: function (event, ui) {
alert(ui.item.value);
}
});
I was using JQuery Autocomplete as a combobox and your needs work well with me and you can review the following code may be help you :
(function( $ ) {
$.widget( "ui.combobox", {
_create: function() {
var input,
self = this,
select = this.element.hide(),
selected = select.children( ":selected" ),
value = selected.val() ? selected.text() : "",
wrapper = $( "<span>" )
.addClass( "ui-combobox" )
.insertAfter( select );
input = $( "<input>" )
.appendTo( wrapper )
.val( value )
.addClass( "ui-state-default" )
.autocomplete({
delay: 0,
minLength: 0,
source: function( request, response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
response( select.children( "option" ).map(function() {
var text = $( this ).text();
if ( this.value && ( !request.term || matcher.test(text) ) )
return {
label: text.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>" ),
value: text,
option: this
};
}) );
},
select: function( event, ui ) {
ui.item.option.selected = true;
self._trigger( "selected", event, {
item: ui.item.option
});
},
change: function( event, ui ) {
if ( !ui.item ) {
var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
valid = false;
select.children( "option" ).each(function() {
if ( $( this ).text().match( matcher ) ) {
this.selected = valid = true;
return false;
}
});
if ( !valid ) {
// remove invalid value, as it didn't match anything
$( this ).val( "" );
select.val( "" );
input.data( "autocomplete" ).term = "";
return false;
}
}
}
})
.addClass( "ui-widget ui-widget-content ui-corner-left" );
input.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
};
$( "<a>" )
.attr( "tabIndex", -1 )
.attr( "title", "Show All Items" )
.appendTo( wrapper )
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass( "ui-corner-all" )
.addClass( "ui-corner-right ui-button-icon" )
.click(function() {
// close if already visible
if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
input.autocomplete( "close" );
return;
}
// work around a bug (likely same cause as #5265)
$( this ).blur();
// pass empty string as value to search for, displaying all results
input.autocomplete( "search", "" );
input.focus();
});
}
});
})( jQuery );
and I think your needs in the following part but I don't know how to use that in your code :
source: function( request, response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
response( select.children( "option" ).map(function() {
var text = $( this ).text();
if ( this.value && ( !request.term || matcher.test(text) ) )
return {
label: text.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>" ),
value: text,
option: this
};
}) );
},
You can try something like this, based on code from jQueryUI: how can I custom-format the Autocomplete plug-in results?
function monkeyPatchAutocomplete() {
$.ui.autocomplete.prototype._renderItem = function (ul, item) {
var matchstring = [];
$.each(this.term.split(""), function(index, c){
matchstring.push("^"+c+"|\b"+c);
});
var output = item.label.replace(new RegExp("(" + matchstring.join("|") + ")", "gi"), '<span class="ui-menu-item-highlight">$1</span>');
return $("<li>")
.append($("<a>").html(output))
.appendTo(ul);
};
}
$(function () {
monkeyPatchAutocomplete();
});
May or may not work. The idea is to get a Regex string like ^G|\bG for each character. I'm sure this misses quite a few cases, so keep working on it.
Edit: working jFiddle. http://jsfiddle.net/9MC5M/ Like the code above but with a few bug fixes. The search is deliberatly broken, it just returns all items to showcase the highlighting.

codeigniter - how to display a popup form in a div tag using jquery

I'd like have a button on my page that display a form (in a div) which includes text box and two buttons.
I'm not too familiar yet with jquery but I did do some reading and have tried to base my code on an example found here at: http://jqueryui.com/demos/dialog/#modal-form
I have a button that looks like:
<input type='button' class='btn btn-info' value='Change VLAN' id='changevlan'/>
and a div that contains the details of the pop form that I want:
<div id="dialog-form" title="Change Vlan">
<p>You must supply a new vlan number</p>
<form>
<fieldset>
<label for="vlan">Vlan Number:</label>
<input type="text" name="vlan" id="vlan" class="text ui-widget-content ui-corner-all" />
</fieldset>
</form>
</div>
And then at the bottom of my page, i have included the jquery and jquery ui libraries (I loaded at bottom for faster page loading) and I have the following javascript: (I based it off the example i mentioned at the beginning of this post.)
<script type="text/javascript">
$(function() {
// a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!
$( "#dialog:ui-dialog" ).dialog( "destroy" );
var vlan = $( "#vlan" ),
tips = $( ".validateTips" );
function updateTips( t ) {
tips
.text( t )
.addClass( "ui-state-highlight" );
setTimeout(function() {
tips.removeClass( "ui-state-highlight", 1500 );
}, 500 );
}
function checkLength( o, n, min, max ) {
if ( o.val().length > max || o.val().length < min ) {
o.addClass( "ui-state-error" );
updateTips( "Length of " + n + " must be between " +
min + " and " + max + "." );
return false;
} else {
return true;
}
}
function checkRegexp( o, regexp, n ) {
if ( !( regexp.test( o.val() ) ) ) {
o.addClass( "ui-state-error" );
updateTips( n );
return false;
} else {
return true;
}
}
$( "#dialog-form" ).dialog({
autoOpen: false,
height: 300,
width: 350,
modal: true,
buttons: {
"Change Vlan": function() {
var bValid = true;
allFields.removeClass( "ui-state-error" );
bValid = bValid && checkLength( vlan, "vlan", 1, 1 );
bValid = bValid && checkRegexp( vlan, /^([0-9])+$/i, "vlan must be numeric." );
if ( bValid ) {
//this is where I need to redirect to another URL passing the vlan number.
$( this ).dialog( "close" );
}
},
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
allFields.val( "" ).removeClass( "ui-state-error" );
}
});
$( "#changevlan" )
.button()
.click(function() {
alert('in here');
$( "#dialog-form" ).dialog( "open" );
});
});
</script>
As you can see I inserted an alert statement to ensure that i was getting into the javascript. But I don't get the alert message. And the contents of the div form just show up on the main page when it's initially rendered.
What I've checked so far:
I've tried to double check that the name of my button that should trigger the div form display matches the name of the variable i'm looking for in the javascript function:
$( "#changevlan" )
.button()
.click(function() {
alert('in here');
$( "#dialog-form" ).dialog( "open" );
});
I've also made sure that my div form is called #dialog-form
But I'm not too sure what else to try. If you ahve any suggestions, I'd appreciate it. I also need to know how to access the contents of the text box and then redirect the user to a new controller and method, passing the vlan number as a parameter.
Maybe I can just do a window.location type of thing...
Thanks.
u dont need more libraries, just make a simple jQueryUI .dialog, inside the "div" element for the dialog place some inline php from CI, something like <div id="dlgPopUpForm"><?= $this->load->view('dialogView.php'); ?></div>, then build your form in the dialogView.php of course.
At run time, the php wil be read into the div and the jquery options u use to create the dialog will handle the rest. something like $("#dlgPopUpForm").dialog({ autoOpen: false, modal: true }); $("#someButton").click(function(e){ $("#dlgPopUpForm").dialog("open"); });
dont forget to include your javascript for the form on the form view page (dialogView.php in my example)
maybe when i'm not so lazy, i'll make ya an example later today, though, its pretty straight forward

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

world countres list with cities

is there any solution to show user all countries and after select country it reselect all cities of its country? be best with script selecting
p.s. russian name of countries
Sure, there's a solution. You could have Country and City models with Id and Name properties:
public class Country
{
public int Id { get; set; }
public string Name { get; set; }
}
public class City
{
public int Id { get; set; }
public string Name { get; set; }
}
And an action that would give you all cities in a country:
public class CountriesController : Controller
{
public ActionResult Index()
{
IEnumerable<Country> countries = Repository.GetCountries();
return View(countries);
}
}
public class CitiesController: Controller
{
public ActionResult Index(string countryId)
{
IEnumerable<City> cities = Repository.GetCities(countryId);
return Json(cities);
}
}
And have a view similar to this:
<%= Html.DropDownList("selectedCountry", new SelectList(Model, "Id", "Name")) %>
<%= Html.DropDownList("selectedCity", Enumerable.Empty<City>()) %>
Then setup javascript:
$(function() {
$('#selectedCountry').change(function() {
var selectedCountry = $(this).val();
$.getJSON('/cities/index', { countryId: selectedCountry }, function(cities) {
var citiesSelect = $('#selectedCity');
citiesSelect.empty();
$(json).each(function(i, city) {
citiesSelect.append('<option value="' + city.Id + '">' + city.Name + '</option>');
});
});
});
});
I thing, better solution is use JSON to exists database. For example you can use geonames.org
http://jqueryui.com/demos/autocomplete/#remote-jsonp
Example:
<meta charset="utf-8">
<style>
.ui-autocomplete-loading { background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat; }
#city { width: 25em; }
</style>
<script>
$(function() {
function log( message ) {
$( "<div/>" ).text( message ).prependTo( "#log" );
$( "#log" ).attr( "scrollTop", 0 );
}
$( "#city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://ws.geonames.org/searchJSON",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
response( $.map( data.geonames, function( item ) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
});
</script>
<div class="demo">
<div class="ui-widget">
<label for="city">Your city: </label>
<input id="city" />
Powered by geonames.org
</div>
<div class="ui-widget" style="margin-top:2em; font-family:Arial">
Result:
<div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>
</div><!-- End demo -->
<div class="demo-description">
<p>The Autocomplete widgets provides suggestions while you type into the field. Here the suggestions are cities, displayed when at least two characters are entered into the field.</p>
<p>In this case, the datasource is the geonames.org webservice. While only the city name itself ends up in the input after selecting an element, more info is displayed in the suggestions to help find the right entry. That data is also available in callbacks, as illustrated by the Result area below the input.</p>
</div><!-- End demo-description -->
If you just need a one-time list (and not something that's continuously updated), then manually scraping the Russian Wikipedia page for list of countries isn't too bad. Could do something similar with a list of cities as well, but trying to get a complete list of cities is somewhat foolhardy. I'd try and limit it to the top 200 in the world or so.
Note: I just assume that's the page for list of countries because I speak no Russian but that's the first result I got when I searched for it.

Categories