Select2 - create ajax with pre-loaded options - javascript

I have a fairly simple requirement set, but cannot for the life of me figure out how to achieve it with Select2...
I would like to have an input on the page
Which the user can type into to trigger an AJAX call
Which also displays a pre-loaded list of options that the user can click on instead of typing to trigger the AJAX.
If you close (blur) the input and then reopen it again then the previously loaded AJAX responses should still be displayed (instead of the options being blank and you having to start typing to load them again).
I can do #1 and #2 (or #1 and #3 of course!), but I cannot get all three requirements in one input field. I've not found any way to do #4.
Effectively, to achieve #3, I guess I'm looking for a way to inject my shortlist into what are normally the ajax-returned options and use something like #4 to make sure these are not cleared when the field is opened.
Is there a way to initialise the (normally Ajax loaded) options for a Select2 field? I've tried passing in data but it doesn't work, I tried using initSelection until I realised that wasn't relevant, I've tried all sorts of things, but to no avail...
Hopefully this is possible and I've just missed an option somewhere!
P.S. I've read several threads on Stack with similar titles to this but none of them seem to answer this question. If I've missed the vital one just let me know!

I think you can do this if you use Select2's query option, rather than the ajax option. That way you can make the ajax request if any characters have been typed, but show the default list if no characters have been typed.
If your default options are defined like this:
var DEFAULT_OPTIONS = [
{ id: 'def1', text: 'Default Choice 1' },
{ id: 'def2', text: 'Default Choice 2' },
{ id: 'def3', text: 'Default Choice 3' }
];
You could do the following:
var lastOptions = DEFAULT_OPTIONS;
$('#select').select2({
minimumInputLength: 0,
query: function(options) {
if (options.term) {
$.ajax({
type: 'post', // Or 'get' if appropriate
url: 'your_ajax_url',
dataType: 'json',
data: {
term: options.term // Change name to what is expected
},
success: function(data) {
lastOptions = data;
options.callback({ results: data });
}
});
} else {
options.callback({ results: lastOptions });
}
}
});
jsfiddle

Related

How to serialize dynamic form data to keep maximum UI flexibility?

Due to the nature of my current project, I often find myself having to create HTML <form> elements which must support dynamic add/remove functionality of items for posting collections to the server.
My issue is that I find myself constrained by the name attribute of the form elements because I have to keep track of indices, ex.: Room[1].Tourists[0].Name. This is giving me hard times when I would like, for example, to remove an existing input element from the beginning.
I am currently building these dynamic forms with react.js which is enabling great flexibility, but I was wondering if there was some way that I could collect form data on submit event and just serialize it to match the expected model in the controller's action and post it?
Okay so you just want to solution about this i think you were stuck somewhere in your code that's why i am asking about the sample code no worry back to this try this:
<script type="text/javascript">
$(document).ready(function () {
$("#btn_submit").on('click', function () {
$.ajax({
type: "POST",
url: "Give URL here",
async: false,
data: $("#FormID").serialize(),
success: function (result) {
//Do what you want
},
error: function (response) {
//Do what you want
}
});
});
});
</script>

Select2 with Ajax is not sending request

I'm using Select2 version 4.0.0 and trying to load a remote JSON from a PHP script that returns the already formated data that I need. The problem is that the forces of the darkness are making something, because I just can't send the request, there is no error, but there is no request sent, it just stays so quiet as a devil that I'm almost crying!
I'm using LiveScript and Jade as alternatives to JavaScript and HTML, but I'll translate'em here.
First, my markup defines the selectable field:
<select id="satan-hates-me"></select>
Then, I'm able to make it look like a selectable element:
$("#satan-hates-me").select2({
placeholder: "Hail",
minimumInputLength: 1,
ajax: { // Here that bad things happen, I mean, don't happen
url: "http://localhost/os/backend/TestServiceOrder.php?req=getEquipments",
dataType: "json",
type: "GET",
quietMillis: 50,
data: function(term) { return { term: term } },
results: function(data) { return data; }
}
});
I'm performing this wrapped in a load function, after page loading, it looks like a selectable, but sends no requests, and the script returns me exactly the required format, as example:
[{id: 1, text: "Sadness"}, {id: 2, text: "Depression"}]
And here goes. I can design compilers but I can't in the world make a plugin work with Ajax! Can somebody help me, please?
Finally resolved the issue.
<input> is not supported in select2 v4
.You have to use <select> element instead
In my case, it was a general select2-call of .select2-Elements in the footer of all my templates:
$('.select2').select2();
Event though my select for the Ajax-Request didn't have that class at all (I called it via an id), I had to change the above to
$('select.select2').select2({theme: 'classic'});
I guess select2() creates several elements with the class .select2, so that might interfere

Jquery Select2 V4 in Ajax mode not working in IE9

Using Select2 4.0 in my forms' select elements, those intented to be filled dynamically in Ajax mode are not working in IE9. It displays an empty select with no placeholder.
The ones in classic mode (pre-filled select lists) are displaying and working (select2 search..) correctly.
Using the older version 3.5.2 in other pages, the problem doesn't occur...!
Is this a known issue? Fixable one?
Thx
Here's the JS:
$(".select2Ajax").not(".select2-container").each(function(){
var min = $(this).data('min'); // 3
var configs = {
"width":"100%",
language: $locale, // 'fr'
ajax: {
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term
};
},
processResults: function (data, page) {
return {
results: data
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; },
minimumInputLength: min
};
$(this).select2(configs);
})//.each
The HTML:
<select id="contrat_kam" name="contrat[kam]" class="select2Ajax form-control" data-min="3" data-ajax--url="/My/Ajax/Source/url-returning-json-formatted-list/from-search-term">
<option value="">Here is my intitial placeholder</option>
</select>
And an example of what's returned form the server when typing into the select2 field, in a normal client (Chrome):
[{"id":"75484567","text":"Bestnameever Ronald"},{"id":"12344568","text":"Nameofdude C\u00e9dric"},{"id":"01202795","text":"SecondDudesName John"},{"id":"00709297","text":"Doe John"}]
Thank you
Ok I solved my problem, but it wasn't a JS/IE problem.
I am working under Symfony 2. The problem appeared after the form submit. Having a validation error, Symfony displays the form page again with the errors on the fields.
I was using Select2 in AJAX mode because the choices list was way too heavy to handle, nearly causing the browser to crash with more than 7000 options to display..
So I created the select (sf2 entity choice list) with an empty array for choices list.
BUT
If you try to save your form with the new value, which was NOT in the (empty) original choice list, SF doesn't validate it, and throws a validation error.
SO
you have to add a form PRE_SUBMIT event listener, to add the select with your selected value in it, to your formType.
Which is complete other subject :)
The problem was that the new select that I defined in the form event listener did'nt have the correct parameters (class, data attributes..), preventing the select2 to work.
My bad!
So the subject would rather find his place in a Symfony 2 thread..

Using Twitter's typeahead.js - calling my WebAPI, how to fill the drop down list in my typeahead input text box?

This is my first time using Twitter's typeahead.js. I've got parts of it working, but what's not working is when I type ahead, the drop down list under the input text box is supposed to fill with values, but instead for me it says "undefined".
Here's my client-side code:
$(document).ready(function () {
$('input.typeahead-devs').typeahead({
name: 'movies',
remote: {
url: 'http://localhost:61182/api/SixFilm/GetMovies?term=%QUERY',
dataType: 'json',
}
});
});
The URL in the code above works and returns valid JSON. Here's my UI and my Firebug output:
I have a feeling I'm getting "undefined" because my "typeahead" doesn't know what to put for the values in the drop down list. Is there a particular variable I'm missing in my .typeahead call? How would I construct my typeahead correctly so that I get values in my drop down list?
I solved my problem. I needed valueKey. valueKey in my example is "Name", which is what I want to populate the drop down list:
$(document).ready(function () {
$('input.typeahead-devs').typeahead({
name: 'movies',
remote: {
url: 'http://localhost:61182/api/SixFilm/GetMovies?term=%QUERY',
dataType: 'json',
}
valueKey: "Name",
});
});

how to use JSON for an error class

Hey all. I was fortunate enough to have Paolo help me with a piece of jquery code that would show the end user an error message if data was saved or not saved to a database. I am looking at the code and my imagination is running wild because I am wondering if I could use just that one piece of code and import the selector type into it and then include that whole json script into my document. This would save me from having to include the json script into 10 different documents. Hope I'm making sense here.
$('#add_customer_form').submit(function() { // handle form submit
The "add_customer_form" id is what I would like to change on a per page basis. If I could successfully do this, then I could make a class of some sort that would just use the rest of this json script and include it where I needed it. I'm sure someone has already thought of this so I was wondering if someone could give me some pointers.
Thanks!
Well, I hit a wall so to speak. The code below is the code that is already in my form. It is using a datastring datatype but I need json. What should I do? I want to replace the stupid alert box with the nice 100% wide green div where my server says all is ok.
$.ajax({
type: "POST",
url: "body.php?action=admCustomer",
data: dataString,
success: function(){
$('#contact input[type=text]').val('');
alert( "Success! Data Saved");
}
});
Here is the code I used in the last question, minus the comments:
$(function() {
$('#add_customer_form').submit(function() {
var data = $(this).serialize();
var url = $(this).attr('action');
var method = $(this).attr('method');
$.ajax({
url: url,
type: method,
data: data,
dataType: 'json',
success: function(data) {
var $div = $('<div>').attr('id', 'message').html(data.message);
if(data.success == 0) {
$div.addClass('error');
} else {
$div.addClass('success');
}
$('body').append($div);
}
});
return false;
});
});
If I am right, what you are essentially asking is how you can make this piece of code work for multiple forms without having to edit the selector. This is very easy. As long as you have the above code included in every page with a form, you can change the $('#add_customer_form') part to something like $('form.json_response'). With this selector we are basically telling jQuery "any form with a class of json_response should be handled through this submit function" - The specific class I'm using is not relevant here, the point is you use a class and give it to all the forms that should have the functionality. Remember, jQuery works on sets of objects. The way I originally had it the set happened to be 1 element, but every jQuery function is meant to act upon as many elements as it matches. This way, whenever you create a form you want to handle through AJAX (and you know the server will return a JSON response with a success indicator), you can simply add whatever class you choose and the jQuery code will take over and handle it for you.
There is also a cleaner plugin that sort of does this, but the above is fine too.
Based on your question, I think what you want is a jQuery selector that will select the right form on each of your pages. If you gave them all a consistent class you could use the same code on each page:
HTML
<form id="some_form_name" class="AJAX_form"> ... </form>
Selector:
$('form.AJAX_form")

Categories