Select2 4.0 caching data from ajax call to a variable - jquery-select2

Is there a way to cache ajax results to a variable in select2 4.0 so the next time the box is clicked it pulls from the local cache vs doing ajax call again?

Store your result in a global variable and check the variable has contents before doing ajax call.
OR
Try using the ajax.processResults option to process the data returned from the server before passing it to Select2.
enter code here$('select').select2({
ajax: {
url: '/example/api',
processResults: function (data) {
//add data to global variable
return {
results: data.items
};
}
}
});

Related

Make Select2 fetch data only once

I'm using Select2 builtin AJAX to load a tiny list of items. Select2 loads the entire list on first selection (good) but reloads the JSON feed every time the user tries to change his selection or type to filter items (and that means a new AJAX request for each typed letter!).
At A request is being triggered on every key stroke, can I delay this? we can read:
By default, Select2 will trigger a new AJAX request whenever the user
changes their search term. You can set a time limit for debouncing
requests using the ajax.delay option.
$('select').select2({
ajax: {
url: '/example/api',
delay: 250
}
});
This will tell Select2 to wait 250 milliseconds before sending the request out to your API.
... but it doesn't. Seriously. I've also tried the undocumented minimumInputLength property shown in examples but it doesn't seem to do anything.
Is it even possible to make Select2 fetch data only once?
The select2 ajax parameter sets off the ajax call every time the user changes her/his input. If you want to load your list only once, just load it via a normal ajax call when your page is loaded and set the result into the data attribute of your select2 like this:
var dataList;
$.ajax({
url : '/example/api',
success : function(data) {
dataList = data;
},
async : false
});
$('select').select2({
data: dataList
});
It is working for me. I tested it using a large delay: delay: 3000
The AJAX reqeust is indeed delayed 3 secs after the last keystroke.
It also works when deleting characters with the backspace key.
I'm using select2.full.js v4.0.3. Hope this helps.
Let me know if this solution would work for you:
1) bind an onChange action to your select element:
<select name="variable" onChange="loadyourlist($('option:selected',this).val());">
<option value="#">Select State</option>
<option value="1">State 1</option>
</select>
2) Make your request inside loadyourlist function, but check if it has been called before:
window.called = 0; //initial state
function loadyourlist(value){
if(!window.called){ //not called before
//make your ajax call
window.called = 1; //increment to avoid furter calls
}
}

Ajax call on ruby on rails

I have a ajax call using ruby on rails. I'm getting a success but I don't know how to use the data result of the ajax call.
$.ajax({
url: "/search/get_listing?listing_id" + id,
dataType: 'JSON',
success: function(data) {
var listing = JSON.parse(data);
$("#modalPrice").html(data.city);
}
});
Controller:
#listings_data = Listings.find_by(id: params[:id])
render :json => #listings_data.to_json
Using data.city won't work. I'm expecting to get the values retrieve from the model by simply putting . on the variable
var listing = JSON.parse(data);
Still no luck. Help guys. Thanks!
JSON.parse is Ruby code, API of JSON gem. How can you guys use that in Javascript :)
jQuery can process JSON object data directly. Just use:
success: function(data) {
$("#modalPrice").html(data.city);
}
For example, you can render in the controller:
render :json => { :city => #listings_data }
On the JS:
success: function(data) {
var listing = data.city;
}
I'm having similar problems everytime I use AJAX in rails since the response seems to differ depending on how you return the value or how you are handling the success in JS. Try this:
success: function(data, status, xhr) {
var listing = JSON.parse(xhr.responseText);
$("#modalPrice").html(data.city);
}
I usually use Firebug (Firefox Plugin) to set a breakpoint in my success handlers to check the arguments where exactly the response is in. Sometimes it's in the first value, sometimes in some other and then it may be xhr.response or even xhr.responseText. It's confusing me every time.
To use Firebug for this, press F12 on your page, select the 'Script' pane and find the code you want to check. Click next to the row number of your code where you want your breakpoint. In this case, you could've chosen the var listing line. When the code is executed (after your click), the browser will stop there and you can check the passed arguments on the right side.

jQueryUI autocomplete won't allow me to continue typing whilst it is busy searching initial set of characters

I've got a Google Searchbar-type input field. When I type in a couple characters and wait for half a second it runs the ajax call to an external website I've set in the "source" function of the autocomplete code and once it has returned the results it returns it to the screen (like it should).
The problem is that while the ajax call is being run to fetch the results it won't allow me to continue typing in the input field until the ajax call has completed.
How can I get it to allow me to continue typing while the ajax call is being made?
Here is my jQuery function:
$('#googleSearchbar').autocomplete({
minLength: 2,
autoFocus: true,
delay: 500,
source: function (request, response) {
results = $.parseJSON($(this).callJson('post', 'http://my_external_url', {
data: request.term
}));
response(results);
},
error: function (err) {
console.error('ERROR : ' + err);
return false;
}
});
I have a hunch you are blocking the browser when making your AJAX request. This line:
results = $.parseJSON($(this).callJson('post', 'http://my_external_url', {
data: request.term
}));
Makes me think that $(this).callJson(...) is a synchronous request, which is going to lock up the entire browser for the duration of the request.
You need to make an asynchronous request and call the response function when that request completes. This should stop the browser from locking up.

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.

jQuery block UI exceptions

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!

Resources