How do I add headers to a jqueryui autocomplete call? - jquery-ui

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!

Related

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

changepage after loadpage with variable posted

I would like to fire a changepage after a loadpage.
Below is the code I use.
After a submit, a database action is fired at an external site (with loadPage). That works.
Next I would like to change to another page with the guid (unique ID) variable posted.
I can't get this working.
Hope somebody can. Thanks in advance.
$(document).on('pageinit', '#page1', function(){
$('form').submit(function(){
var guid = GUID();
$.mobile.loadPage( "http://domain.com/dbaction.php?guid="+guid, {
type: "post",
data: $("form#addtegel").serialize()
});
return false;
$.mobile.changePage ($("#page2"),{ transition: "slideup"} );
});
});
$(document).on('pageinit', '#page2', function(){
DoSomething(guid);
});
First, you need to make guid a global variable. At the moment, it's local to your form submission, so it cannot be accesses outside that form submit action.
Second, instead of using loadPage() - which is jQuery Mobile's internal function called by changePage() by the way - use $.ajax() like this:
var guid;
$(document).on('pageinit', '#page1', function(){
$('form').submit(function(){
window.guid = GUID();
$.ajax({
url: "http://domain.com/dbaction.php?guid="+guid,
type: "post",
data: $("form#addtegel").serialize(),
success: function() {
$.mobile.changePage ($("#page2"), { transition: "slideup"} );
}
});
return false;
});
});
$(document).on('pageinit', '#page2', function(){
DoSomething(window.guid);
});
Also, please be aware that mixing GET and POST data is a very bad habit. I'm talking about this url: "http://domain.com/dbaction.php?guid="+guid
There should only be GET or POST data present in a single request, not both. Would it not be possible to pass guid to dbaction.php in the POST (using a hidden field in your form)?

Why ajax success is called once?

Why, if i write html method in javascript, it's called only once, but if i have only alert, it's calles every time, i change wy value in input (blur).
$(".quantity").blur(function() {
console.log("upd");
$.ajax({
url: "/line_items/update_quantity/"+$(this).attr("id"),
type: "GET",
data: {quantity: $(this).val()},
success: function(text)
{
alert(text);
$('.right').html(text);
},
error: function(){
alert('Ошибка javascript');
},
dataType : "html"
});
});
I need reload html partial after every blur...
Try doing this..
$(document).on('blur', '.quantity', function() {
// place your code here
});
I suspect you're replacing the dom element that the original blur binding is applied against. If you do that you remove the event handler. On() will keep it alive.
If .quantity is dynamic element (I think so) then try
$(document).delegate('.quantity', 'blur', function() {
// code
});
read here about delegate()

jQueryUI AutoComplete Remote Source misdirected

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

Resources