jQuery block UI exceptions - jquery-ui

I am using JQuery UI plugin blockUI to block UI for every ajax request. It works like a charm, however, I don't want to block the UI (Or at least not show the "Please wait" message) when I am making ajax calls to fetch autocomplete suggest items. How do I do that? I am using jquery autocomplete plugin for autocomplete functionality.
Is there a way I can tell the block UI plug-in to not block UI for autocomplete?

$('#myWidget').autocomplete({
source: function(data, callback) {
$.ajax({
global: false, // <-- this is the key!
url: 'http:...',
dataType: 'json',
data: data,
success: callback
});
}
});

Hm, looks to be a missing feature in jquery :)
You could use a global flag to indicate if it is a autocomplete call and wrap it in a general autcompletefunction
var isAutoComplete = false;
function autoComplete(autocomplete){
isAutoComplete = true;
if($(autocomplete).isfunction())
autocomplete();
}
$(document).ajaxStart(function(){if(!isAutoComplete)$.blockUI();}).ajaxStop(function(){isAutoComplete = false;$.unblockUI();});
It's not a nice solution but it should work...

try using a decorator
$.blockUI = function() {
if (condition_you_dont_want_to_block) {
return;
}
return $.blockUI.apply(this, arguments);
}
or you can write your own block function that is smarter
function my_blockUI() {
if (condition_you_dont_want_to_block) {
return;
}
$.blockUI();
}
$(document).ajaxStart(my_blockUI).ajaxStop($.unblockUI);

You can set blockUI to work for all functions on the page by adding to a global jQuery event handler. To make sure it doesn't get called on autocomplete ajax calls we have to determine if the call is an autocomplete call or not. The problem is that these global functions don't have that much information available to them. However ajaxSend does get some information. It gets the settings object used to make the ajax call. the settings object has the data string being sent. Therefore what you can do is append to every data string in every ajax request on your page something like:
&notautocomplete=notautocomplete
For example:
$.ajax({data:"bar=1&foo=2&notautocomplete=notautocomplete"})
Then we can put this code in your document ready section before anything else:
$(document).ajaxSend(
function (event, xhr, ajaxOptions){
if(ajaxOptions.data.indexOf("notautocomplete") !== -1){
$.blockUI;
}
});
$(document).ajaxStop($.unblockUI);
Of course the other better idea would be to look for something unique in the auto complete requests, like the url, but that depends on which autocomplete plug-in you are using and how you are using it.

using a modal block (block UI) means blocking any inputs from user, I'd suggest plain old throbber to show 'Please wait..' and to block ( set attributes readonly="readonly" ) ur input controls till the ajax request is complete.
The above UI seems to be self conflicting!

Related

jquery mobile 1.4 not updating content on page transition

From the index page, a user clicks a navigation link, the data attribute is passed via ajax, the data is retrieved from the server but the content is not being updated on the new page.
Been stuck for hours, really appreciate any help!
js
$('a.navLink').on('click', function() {
var cat = $(this).data("cat");
console.log(cat);
$.ajax({
url: 'scripts/categoryGet.php',
type: 'POST',
dataType: "json",
data: {'cat': cat},
success: function(data) {
var title = data[0][0],
description = data[0][1];
console.log(title);
$('#categoryTitle').html(title);
$('#categoryTitle').trigger("refresh");
$('#categoryDescription').html(description);
$('#categoryDescription').trigger("refresh");
}
});
});
Im getting the correct responses back on both console logs, so I know the works, but neither divs categoryTitle or categoryDescription are being updated. I've tried .trigger('refresh'), .trigger('updatelayout') but no luck!
This was not intended to be an answer (but I can't comment yet.. (weird SO rules)
You should specify in the question description that the above code IS working, that your problem occurs WHEN your playing back and forth on that page/code aka, using the JQM ajax navigation.
From what I understood in the above comment, you're probably "stacking" the ajax function every time you return to the page, thus getting weird results, if nothing at all.
Is your example code wrapped into something ? If not, (assuming you use JQM v1.4) you should consider wrapping it into $( 'body' ).on( 'pagecontainercreate', function( event, ui ) {... which I'm trying to figure out myself how to best play with..
Simple solution to prevent stacking the ajax definition would be to create/use a control var, here is a way to do so:
var navLinkCatchClick = {
loaded: false,
launchAjax: function(){
if ( !this.loaded ){
this.ajaxCall();
}
},
ajaxCall: function(){
// paste you example code here..
this.loaded = true;
}
}
navLinkCatchClick.launchAjax();

JQuery UI Autocomplete events and empty response

I'm using jQuery UI Autocomplete search and open events. But the open event is only called when the request is successful and there are elements. There does not seem to be an event when the response is successful but empty.
I display and hide a spinner logo when triggering the request, like this :
search: function() {
$('.spinner').show();
},
open: function() {
$('.spinner').hide();
}
This works well when there are elements in the server response but if the server response is empty the spinner stays forever...
Thanks for your answers.
PS : I'm not alone : remove spinner from jquery ui autocomplete if nothing found ;)
As of jQuery UI v1.9 you can do something like the following:
$('#field').autocomplete({
source: source_url,
search: function(event, ui) {
$('#spinner').show();
},
response: function(event, ui) {
$('#spinner').hide();
}
});
This is a known open enhancement for future versions of jQuery UI...
http://bugs.jqueryui.com/ticket/6777
Will have to wait and/or use a workaround (like sending a special response from the server and handle this case in the open event).
If you're stuck on an older version of jQuery ui, the right answer is to use the class ui-autocomplete-loading, which gets added and removed while the request/response is in flight.

JQuery UI Autocomplete Syntax

Can someone help me understand the following code? I found it here.
It takes advantage of the JQuery UI Autocomplete with a remote source. I've commented the code as best I can and a more precise question follows it.
$( "#city" ).autocomplete({
source: function( request, response ) {
//request is an objet which contains the user input so far
// response is a callback expecting an argument with the values to autocomplete with
$.ajax({
url: "http://ws.geonames.org/searchJSON", //where is script located
dataType: "jsonp", //type of data we send the script
data: { //what data do we send the script
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) { //CONFUSED!
response(
$.map(
data.geonames, function( item ) {
return {
label: item.name+(item.adminName1 ? ","+item.adminName1:"")+","+item.countryName,
value: item.name
}
}
)
);
}
});
}
});
As you can see, I don't understand the use of the success function and the response callback.
I know the success function literal is an AJAX option which is called when the AJAX query returns. In this case, it seems to encapsulate a call to the response callback? Which is defined where? I thought by definition of a callback, it should be called on its own?
Thanks!
The response object as defined by the documentation ("Overview" page):
A response callback, which expects a
single argument to contain the data to
suggest to the user. This data should
be filtered based on the provided
term, and can be in any of the formats
described above for simple local data
(String-Array or Object-Array with
label/value/both properties). It's
important when providing a custom
source callback to handle errors
during the request. You must always
call the response callback even if you
encounter an error. This ensures that
the widget always has the correct
state.
so, the 'response' argument is actually a callback, which must be called upon success of the ajax retrieval of autocomplete items.
Since your data will come back via AJAX, your code must update the widget manually. jQueryUI provides an argument as a function so that your code can do that update by calling the function.
You can see the response object defined in the declaration of the function used for the source option:
source: function( request, response )
You could even take the AJAX call out of the equation and do something like this:
source: function(request, response) {
response([{label:'foo', value: 'foo'},{label:'bar', value:'bar'}]);
}
Would immediately call the response callback with an array of label/value pairs for the widget.

ASP .NET MVC Ajax link that gets executed onmouseover

In my ASP .NET MVC application i have a link that refreshes "the preview data box" after each click. I've done this using this code:
<%= Ajax.ActionLink("delete", "DeleteItem", new AjaxOptions(){UpdateTargetId="casePreview"}) %>
Now I would like to change the behaviour in such a way that the preview data box is refreshed each time link's onmouseover event is raised.
What's the simplest way to do it?
Use jQuery to fire the click event of the link
$(selector).mouseover(function () {
$(this).click();
});
EDIT: A simplified version of what I described in my comment. Essentially, the mouseover event handler should use some AJAX to retrieve updated information, when the request is complete the UpdateUI function fires and does its work. This particular script would also cause an alert to appear when the element is clicked.
$(selector).mouseover(function() {
$.ajax({
type: "GET",
url: "/my/path/to/someplace",
complete: UpdateUI});
}).click(function() {
alert("tada");
});
function UpdateUI(XMLHttpRequest, textStatus) {
//Update Your UI
}
Unfortunately there is no way to do this using the AjaxHelpers only: you'll have to use javascript directly. For example, you can use jQuery and "register" to the onmouseover event, and than use the Ajax method to call for the refresh of the "preview data box"
You should call jaquery method on onmouseover() event.

jQuery Dialog posting of form fields

I'm trying to do some data entry via a jQuery modal Dialog. I was hoping to use something like the following to gather up my data for posting.
data = $('#myDialog').serialize();
However this results in nothing. If I reference just the containing form instead myDialog then I get all the fields on the page except those within my dialog.
What's the best way to gather up form fields within a dialog for an AJAX submission?
The reason this is happening is that dialog is actually removing your elements and adding them at root level in the document body. This is done so that the dialog script can be confident in its positioning (to be sure that the data being dialog'd isn't contained, say, in a relatively positioned element). This means that your fields are in fact no longer contained in your form.
You can still get their values through accessing the individual fields by id (or anything like it), but if you want to use a handy serialize function, you're going to need to have a form within the dialog.
I've just run into exactly the same problem and since I had too many fields in my dialog to reference them individually, what I did was wrap the dialog into a temporary form, serialize it and append the result to my original form's serialized data before doing the ajax call:
function getDialogData(dialogId) {
var tempForm = document.createElement("form");
tempForm.id = "tempForm";
tempForm.innerHTML = $(dialogId).html();
document.appendChild(tempForm);
var dialogData = $("#tempForm").serialize();
document.removeChild(tempForm);
return dialogData;
}
function submitForm() {
var data = $("#MyForm").serialize();
var dialogData = getDialogData("#MyDialog");
data += "&" + dialogData;
$.ajax({
url: "MyPage.aspx",
type: "POST",
data: data,
dataType: "html",
success: function(html) {
MyCallback(html);
}
});
}
Form element inside dialog is removed from form and moved to the end of the body. You need something like this.
$("#dialog_id").dialog().parent().appendTo($("#form_id"));
jQuery("#test").dialog({
autoResize:true,
width:500,
height:600,
modal: true,
bgiframe: true,
}).parent().appendTo("form");
This works like charm

Resources