jQueryUI AutoComplete Remote Source misdirected - jquery-ui

I have a jQuery AutoComplete for a text box. The code to initialize the AutoComplete is:
$("#SearchBox1").autocomplete({
autoFocus: false,
source: "Home/AutoComplete",
select: function (event, ui) {
alert(ui.item.label);
}
When the URL doesn't contain a path, the jQuery Autocomplete works, but when the URL contains something like localhost/home/GoToPage/?page=2, then AutoComplete attempts to use /home/GoToPage/Home/AutoComplete. At this point AutoComplete is completely broken, because it is using a bad path.
Are there any good ways of dealing with this problem?

One possible solution is based off of MadRabbit's comments, and Dan Wellman jQueryUI Autocomplete tutorial at http://net.tutsplus.com/tutorials/javascript-ajax/how-to-use-the-jquery-ui-autocomplete-widget/
$("#SearchBox1").autocomplete({
autoFocus: false,
source: function (request, callback) {
//pass request to server
$.getJSON("Home/AutoComplete?term=" + request.term, request, function (responseData) {
//create array for response objects
var suggestions = [];
//process response
$.each(responseData, function (i, val) {
suggestions.push(val);
});
//pass array to callback
callback(suggestions);
});
},
select: function (event, ui) {
$('#SearchBox1').val(ui.item.label);
}
});

Related

How do I add headers to a jqueryui autocomplete call?

I'm trying to add a http request-header to a jqueryui autocomplete request. I've looked at the documentation on the jquery site and the solution is presented there for ajax requests. I assumed the solution would be similar in my case but I can't get the darn thing to work.
Here is my code. It's wrapped in an angularjs diretive but the call inside the "link" method would be the same without it being inside the directive.
app.directive("buildingSearch", function () {
// I bind the $scope to the DOM behaviors.
function link(scope, element, attributes, controllers) {
//Attach the autocomplete functionto the element
element.autocomplete({
source: 'api/building/unitOrgMdl',
minLength: 2,
//*********
//This is the addition I made as per the jquery documentation that I figured would work but doesn't
headers: {
'Authorization': '122222222222'
},
//*********
select: function (event, ui) {
element.val(ui.item.label);
element.blur();
scope.getbuildings({ data: ui.item })
return false;
}
});
}
// Return the directive confirugation.
return ({
link: link,
restrict: "EA",
replace: true,
scope: {
getbuildings: '&'
}
});
});
I figured it out... and it works great! I cannot ensure it's the best way to do it but it seems pretty solid. I added the following code right before the autocomplete() method.
$.ajaxSetup({
headers: { 'Authorization': '122222222222' }
});
So the new code in it's entirety looks like this.
app.directive("tmBuildingSearch", function (authService) {
// I bind the $scope to the DOM behaviors.
function link(scope, element, attributes, controllers) {
//Attach the autocomplete function to the element
//NEW CODE. This attaches a custom header
$.ajaxSetup({
headers: { 'Authorization': '122222222222' }
});
element.autocomplete({
source: 'api/building/unitOrgMdl',
minLength: 2,
select: function (event, ui) {
element.val(ui.item.label);
element.blur();
scope.getbuildings({ data: ui.item })
return false;
}
});
}
// Return the directive configuration.
return ({
link: link,
restrict: "EA",
replace: true,
scope: {
getbuildings: '&'
}
});
});
I got the idea from another post on Stake Overflow.
How can I add a custom HTTP header to ajax request with js or jQuery?
I hope this helps someone else!
ENHANCEMENT NOTE! I removed this added code from the directive and put it in the main app module so ANY ajax call will get the Authorization header added to it. Works great!

select2 default value for single field

I'm using Jquery Select2 for my project. I want to keep a default value in a single input field when the page is loaded. I tried this by setting initSelection while I'm initiating the select2 component like this.
$(document).ready(function() {
allowClear: true,
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
dataType: 'json',
url: "public/data.php",
data: function (term, page) {
return {
q: term, // search term
component: "map",
all_selected: $("#map-all").hasClass("active"),
parent_value: $("#city").val(),
child_value: ""
};
},
results: function (data, page) { // parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to alter remote JSON data
return {results: data};
}
},
initSelection: function(element, callback) {
return $.getJSON("public/data.php?q="+element.val()+"&component=map&all_selected=false&parent_value=&child_value=", null, function(data) {
if ($.isFunction(callback)) {
return callback(data);
}
});
},
formatSelection: format,
formatResult: format,
});
However this does not work as it is should be.
But, when I make multiple: true, as a select2 option, this works perfectly. How do I do this for single hidden field?
Thanks & Regards!
Okay, I solved this by changing the callback from return callback(data); to return callback(data[0]);. I think the reason behind this is since the field is not a multiple field, it only accepts a single object to the callback function.

Tooltip using jquery ui

Its my first time using the tooltip and have done a lot research on it. I used the jquery website to get most of the information. I intend my tooltip to show dynamic data when a mouse clicks the hyperlink. I added the title to my link and have this code below:
var t = 1000;
$(document).tooltip({
content: '... waiting on ajax ...',
open: function(evt, ui) {
var elem = $(this);
$.ajax({ type: "POST",url:'/GetTooltip/', data: 80140}).always(function() {
elem.tooltip('option', 'content', 'Ajax call complete');
});
setTimeout(function(){
$(ui.tooltip).hide('destroy');
}, t);},
position: {
my: "center bottom-20",
at: "center top",
using: function( position, feedback ) {
$( this ).css( position );
$( "<div>" )
.addClass( "arrow" )
.addClass( feedback.vertical )
.addClass( feedback.horizontal )
.appendTo( this );
}
}
});
I am not fully knowledgeable with the syntax of the ajax call in reference to the always function and how to get the data to show on my tooltip. the GetTooltip returns JSON data, I just want to post to the GetTooltip script and the returned data to show on my tooltip. At the moment my ajax is posting nothing.
Regarding your statement that you are not fully knowledgeable with
always function: the always(function(data|jqXHR, textStatus, jqXHR|errorThrown) { }); is always executed after the ajax request was executed. For more see the documentation deferred.always() Please look also at jqXHR.always(function(data|jqXHR, textStatus, jqXHR|errorThrown) { })
get the returned data to show on the tooltip - see the example in the fiddle
You can find many other answers on stackoverflow. Take a look at this fiddle and let me know if you need more help.
Updated fiddle 2
If have updated the fiddle. You can pass values from the parameters that are returned from the ajax callback. This is a simple wrapper around the ajax call:
function callAjax(elem){
$.ajax({ url: '/echo/json/',
type: 'POST',
contentType:"application/json; charset=utf-8",
dataType:"json",
data: { json: JSON.stringify({ text: 'some text'})}
}).always(
function(data,textStatus, errorThrown)
{
elem.tooltip('option', 'content'
, 'Ajax call complete. Result:' + data.text);
});
}
I am using JSON.stringify(...) above to create a Json-String. This function may be not present in all browsers. So if you run into troubles please use a current chrome / chromium browser to test it.
So you can use the wrapper function inside the tooltip():
$('#tippy').tooltip({
content: '... waiting on ajax ...',
open: function(evt, ui) {
var elem = $(this);
callAjax(elem);
} // open
});
Above you can see that the always method calls an anonymous function with 3 parameters (data, textStatus, errorThrown). To pass the reply from the ajax call you can use data. Above i am only passing a simple object with the propert text. To access it you can use data.text

Jquery UI autocomplete select

I need some help with the code below.
$("#auto_cp").autocomplete({
minLength: 3,
//source
source: function(req, add) {
$.getJSON("friends.php?callback=?", req, function(data) {
var suggestions = [];
$.each(data, function(i, val) {
suggestions.push(val.name);
});
add(suggestions);
});
},
//select
select: function(e, ui) {
alert(ui.item.value);
}
});​
using FireBug, i'm getting this in my console :
jQuery171003666625335785867_1337116004522([{"name":"97300
Cayenne","zzz":"203"},{"name":"97311
Roura","zzz":"201"},{"name":"97312 Saint
Elie","zzz":"388"},{"name":"97320 Saint Laurent du
Maroni","zzz":"391"},{"name":"97351
Matoury","zzz":"52"},{"name":"97354 Remire MontJoly
Cayenne","zzz":"69"},{"name":"97355 Macouria Tonate","zzz":"449"}])
Everything is working very fine, but I don't know how to get the value of 'zzz' on select item.
I tried
alert(ui.item.zzz);
But it doesn't work.
The autocomplete widget expects a data source in array format with either:
Objects containing a label property, a value property, or both
Simple string values
You are currently building up the second (an array of string values), which works fine, but you can also slightly tweak your data as you iterate over it and also supply the other properties in the object:
$("#auto_cp").autocomplete({
minLength: 3,
//source
source: function(req, add) {
$.getJSON("friends.php?callback=?", req, function(data) {
var suggestions = [];
$.each(data, function(i, val) {
suggestions.push({
label: val.name,
zzz: val.zzz
});
});
add(suggestions);
});
},
//select
select: function(e, ui) {
alert(ui.item.zzz);
}
});​
Now, since the array you're supplying the widget contains objects with a name property, you should get autocomplete functionality and also gain access to the zzz property.
Here's a working example (without the AJAX call): http://jsfiddle.net/LY42X/
You're source function is only populating the name. If you want everything from that data structure, do this:
$("#auto_cp").autocomplete({
minLength: 3,
//source
source: function(req, add) {
$.getJSON("friends.php?callback=?", req, function(data) {
var suggestions = [];
$.each(data, function(i, val) {
suggestions.push(val); //not val.name
});
add(suggestions);
});
},
//select
select: function(e, ui) {
alert(ui.item.value.zzz);
}
});​
This seems to be an array of objects... what your may be missing is the "[0]" or in general "[index]".
Please check this: jqueryui.com/demos/autocomplete/#event-select

autocomplete with amplifyjs

I'm trying to use jqueryui autocmplete with amplifyjs. Thats's to be able to switch between call to real server data and some hardcoded one and for additional flexibility.
For now I do not know how to make jqueryui autocomplete call amplify to refresh itself and perform search. I have the following codesnippet:
amplify.request.define('resId', 'ajax', {
url: 'autocmpleteUrl',
dataType: "json",
type: "POST"
});
$(elementId).autocomplete({
minLength: 1,
source: 'some url',
delay: 0,
focus: function (event, ui) {
$(elementId).val(ui.item.label);
return false;
},
select: function (event, ui) {
$(elementId).val(ui.item.label);
return false;
}
}).data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.label + "</a>")
.appendTo(ul);
};
I know in autocomplete part it can both be url and json data. But I can't figure out how to make it deal with amplify and make it so that if user inputs text jquery autocomplete requests amplify, not the url itself. Any ideas?
That's close to what you want, but you've forgotten to pass the search term to your request. Your code should be:
$( elem ).autocomplete({
source: function( request, response ) {
amplify.request( "resId", request, function( data ) {
response( data );
});
});
});
Which will send the search term as the term query parameter. Since you're doing a direct passthrough of the data, this can also be reduced:
$( elem ).autocomplete({
source: function( request, response ) {
amplify.request( "resId", request, response );
});
});
However, in both of these cases you're not handling errors, which means that you can leave the autocomplete in the search state indefinitely. You should use the full amplify.request form to handle errors:
$( elem ).autocomplete({
source: function( request, response ) {
amplify.request({
resourceId: "resId",
data: request,
success: response,
error: function() {
response( [] );
}
});
});
});
I've completed with the following solution:
autocomplete({
source: function(request, response){
amplify.request('resId', function(data){
response(data);
});
},
So you can provide a function to jquery.ui autocomplete and in this function just set the request object and autocomplete data will be filled with data you provide.

Resources