Cancel JQuery UI Autocomplete on form submit - ajax

Greetings,
I have a jqueryui autocomplete input that uses an ajax call to populate the suggestions. How do I ensure when the form is submitted, the suggestions do not appear? I've tried calling the "close" method, but that doesn't work since the form may be submitted before the ajax call has completed.
I have created a fiddle demonstrating my problem here:
http://jsfiddle.net/P7VJf/5/
This is based on the jqueryui demo here:
http://jqueryui.com/demos/autocomplete/#remote-jsonp
Here is the code:
$(function(){
$('form').submit(function(){
/*
when the form is submitted, i want to cancel auto complete
if the ajax call hasn't completed, the suggestions
will still show even if we call close here
*/
$("#city").autocomplete("close");
$('span').html(Math.random() * 3);
return false;
});
$("#city").autocomplete({
delay: 300,
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
});
});
Any help is greatly appreciated.

Building on Xnake's answer, I've got this working by using the 'destroy' command. The trouble is that this totally kills the autocomplete, so you'll then need to reconfigure it again. I did this by refactoring the initial call to autocomplete into a separate function that I can then call again after the destroy command. Like this:
function configureAutocomplete() {
$("#city").autocomplete({
delay: 300,
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
});
}
$(function(){
$('form').submit(function(){
/*
when the form is submitted, i want to cancel auto complete
if the ajax call hasn't completed, so destroy the existing
autocomplete and set up a new one
*/
$("#city").autocomplete("destroy");
configureAutocomplete();
$('span').html(Math.random() * 3);
return false;
});
configureAutocomplete();
});

Have you tried using destroy instead, i.e.: $("#city").autocomplete("destroy"); ?

Related

XMLHTTPRequest dealing with event

I am performing an Ajax (JQuery) request on a php script which iterates. At each iteration I do an "echo" of the value of the loop counter, encoded in JSon. The goal is to manage the display of a progress bar.
By doing this I hoped to intercept and retrieve each of the counter values in a separate response thanks to the "progress" event.
Actually I only have one answer which contains all the counter values.
My research always leads me to information about downloading files, which is not my situation.
Maybe I should use the "onreadystatechange" event, but I don't see how to fit it into my code: $ Ajax parameter or separate function?
If anyone has an idea to solve my problem.
Here is my JS code
function DiffuseOffre(envoi, tab, paquet, dest) {
//$('#cover-spin').show(0);
$("#xhr-rep").css("display", "block");
var server = '/Admin/Offres/DiffuseOffre.php';
$.ajax({
url: server,
type: 'Post',
dataType: 'json',
data: {
envoi: envoi,
tab: tab,
paquet: paquet,
dest: dest
},
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var compteur = evt.text;
$("#xhr-rep").html(compteur);
}
}, false);
return xhr;
},
success: function(msg) {
//$('#cover-spin').css("display", "none");
$('#xhr-rep').css("display", "none");
if (msg.hasOwnProperty('erreur')) {
$("#dialog-erreur").html(msg.erreur);
$("#dialog-erreur").dialog("open");
$("#dialog-erreur").dialog({
width: '600px',
title: msg.title
})
} else {
$("#dialog-message").html(msg.message);
$("#dialog-message").dialog("open");
$("#dialog-message").dialog({
width: '600px',
title: msg.title
})
if (paquet == 1) {
$("#envoi_" + dest).remove();
$("#diffuser").remove();
}
if (msg.hasOwnProperty('encours')) {
$("#en_cours").html(msg.encours);
}
if (msg.hasOwnProperty('fieldset')) {
$("#" + msg.fieldset).remove();
}
}
}
})
}

Use select2 ajax data to update hidden inputs

I am having trouble updating hidden inputs using data retrieved from Select2 Ajax.
Please see my code:
var select2_town = $('.select-test select').select2({
ajax: {
url : ajax_var.url,
dataType: 'json',
type: 'post',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page,
};
},
processResults: function (data, page) {
return {
results: $.map(data, function (item) {
return {
id: item.id, //eg 1149
town: item.place_name, //eg Reading
county: item.county, //eg Berkshire
country: item.country,
data: item
};
})
};
},
cache: true;
},
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 1,
templateResult: function (item) { return ('<p>' + item.town + ' - ' + item.county + '</p>'); },
templateSelection: function (item) { return (item.town); },
});
This code works fine for me. My issue is what happens after a value is selected.
I would like to update my hidden input ids "#town","#county" and "#country" with town,county and country respectively through an 'change' event.
I have seen many SO examples but they all stop at $(this).select2('data')[0];but do not expand on it.
Weird thing is that the following script displays the correct value in console log. but ALWAYS only apply the object id to #country.
select2_town.on('change', function() {
var obz = $(this).select2('data')[0].country;
console.log(obz);//displays Reading in console
$("#country").attr("value",obz); //displays 1149
});
This actually works.
I had another function that was adding the ID hidden in another file. I deleted that and then the script worked as I wanted it to.
Regards
Thanks

JSON, jQueryUI Autocomplete, AJAX - Cannot get data when array is not local

I have searched stackoverflow, as well as the web for some insight into how to get the jQueryUI Autocomplete plugin working with my JSON data, and I'm at a loss. I had it working like a charm with a local data array. I was able to pull values and build html.
I ran into a problem when I had to pull JSON form this source:
/Search/AjaxFindPeopleProperties2
?txtSearch=ca pulls up the test data that I am trying to loop through, when I type in 'ca' to populate the autocomplete list. One of the problems is that ?term=ca is appended to the url instead of ?txtSearch=ca and I'm not sure how to change it.
This is an example of the data:
{
"MatchedProperties": [
{
"Id": 201,
"Name": "Carlyle Center",
"Description": "Comfort, convenience and style are just a few of the features you'll ...",
"ImageUrl": "/Photos/n/225/4989/PU__ThumbnailRS.jpg"
}
]
}
...and here is the ajax call I'm trying to implement:
$(document).ready(function () {
val = $("#txtSearch").val();
$.ajax({
type: "POST",
url: "/Search/AjaxFindPeopleProperties2",
dataType: "json",
data: "{}",
contentType: "application/json; charset=utf-8",
success: function (data) {
$('#txtSearch').autocomplete({
minLength: 0,
source: data.d, //not sure what this is or if it's correct
focus: function (event, ui) {
$('#txtSearch').val(ui.item.MatchedProperties.Name);
$.widget("custom.catcomplete", $.ui.autocomplete, {
//customize menu item html here
_renderItem: function (ul, item) {
return $("<li class='suggested-search-item" + " " + currentCategory + "'></li>")
.data("item.autocomplete", item)
.append($("<a><img src='" + item.MatchedProperties.ImageUrl + "' /><span class='name'>" + item.MatchedProperties.Name + "</span><span class='location'>" + "item.location" + "</span><span class='description'>" + item.MatchedProperties.Description + "</span></a>"))
.appendTo(ul);
},
_renderMenu: function (ul, items) {
var self = this,
currentCategory = "Properties Static Test Category";
$.each(items, function (index, item) {
if (item.category != currentCategory) {
ul.append("<li class='suggested-search-category ui-autocomplete-category'>" + currentCategory + "</li>");
//currentCategory = item.category;
}
self._renderItem(ul, item);
});
}
}//END: widget
//return false;
},
select: function (event, ui) {
$('#txtSearch').val(ui.item.MatchedProperties.Name);
//$('#selectedValue').text("Selected value:" + ui.item.Abbreviation);
return false;
}
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
}); //END ajax
}); //END: doc ready
and I'm initializing here:
<script type="text/javascript">
//initialize autocomplete
$("#txtSearch").autocomplete({ //autocomplete with category support
/*basic settings*/
delay: 0,
source: "/Search/AjaxFindPeopleProperties2",
autoFocus: true,
minLength: 2 //can adjust this to determine how many characters need to be entered before autocomplete will kick in
});
//set auto fucus
$("#txtSearch").autocomplete("option", "autoFocus", true);
</script>
any help would be great...
Thanks!

Jquery UI Autocomplete Ajax JSONP return is broken in JQ UI Version 1.8.6

Ive been using the code below for my auto-completes on my form for a while , but after updating jquery ui to version 1.8.6 from 1.8rc3 it has broken the formatting of the JSONP return. The returned data is no longer formatted html, but instead it is a string. Any Ideas?
Update: JS Fiddle included, using the jquery ui demo and html in the data
http://jsfiddle.net/blowsie/ejLPg/
$("#companyname").autocomplete({
source: function (request, response) {
$.ajax({
url: turl,
dataType: "jsonp",
data: {
maxRows: 9,
name_startsWith: request.term
},
success: function (data) {
response($.map(data, function (item) {
return {
label: "<span class='ui-menu-item-title'>" + item.name.toLowerCase() + "</span><span class='ui-menu-item-subtitle'>" + item.address1.toLowerCase() + ' ' + item.post_code.toLowerCase() + '</span>',
value: item.name_id
}
}))
}
})
},
minLength: 3,
delay: 50,
select: function (event, ui) {
LoadGivenCompany(ui.item.value);
},
open: function () {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
},
focus: function () { return false }
});
Thanks in advance
I looked into the source code of autocomplete of version 1.8.6 and found out that item creation uses text method instead of the html method. They suggest at jQuery.ui to change style using the theme roller of by altering the widget specific classes in the css file.
See Autocomplete#theming.
What i would do is find the place that they push the text in the element and change the method call back to html and test it out.
Turns out by using the .data(), after the autocomplete allows you to format the data
$(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,
test: 'hahahah'
}
}));
}
});
},
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");
}
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "<br>" + item.test + "</a>" )
.appendTo( ul );
};
});
http://jsfiddle.net/blowsie/ejLPg/3

jQuery DoubleSelect/Cascade/Dependent/WalkRight Select Menus w/ Ajax Support?

Where you can pick an item from a <select> menu and then it populates a second <select> menu.
It goes by too many names and there are too many implementations. I'm looking for an up-to-date one (works well with the latest version of jQuery) that can pull the data using Ajax.
Can anyone recommend a good plugin?
// simple code but can be improved for need
function getListBoxValue(obj) {
obj = $.extend({
url: "",
bindObj: null,
emptyText: "exception",
postValues : {},
onComplete: function () { return true; },
onError: function () { return false; }
}, obj);
$.ajax({
url: obj.url,
data: obj.postValues,
type: "POST",
dataType: "JSON",
success: function (json) {
var options;
$.each(json, function (i, e) {
options += "<option value='" + e.Value + "'>" + e.Text + "</option>";
});
$(obj.bindObj).html(options);
obj.onComplete(obj);
},
error: function (e, xhr) {
$(obj.bindObj).html("<option value='-1'>" + obj.emptyText + "</option>");
obj.onError(obj);
}
});
}
// server response data json
[{ "Value": 1, "Text": "text 1 " },{ "Value": 2, "Text": "text 2"}]
getListBoxValue({
url: responseJsonDataURL, // example
bindObj: $("select#YourID"), // example
emptyText:"exception text", // example
postValues: {"id": 45}, // example
onComplete: _onCompleteFunction, // optional
onError: _onErrorFunction // optional
})

Resources