I'm using select2 plugin with remote ajax data. I can see the results in the dropdown but can't select them. I want the results to be selectable and placed into the field after selection. I think the problem is with passing the id, I don't know how to pass it correctly.. Any ideas?
my json for ?tag_word=for ...there is no id
results: [{text: "fort"}, {text: "food"}]
Here the code:
<select class="js-data-example-ajax" style="width:100%">
<option selected="selected">asdasd</option>
</select>
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet" />
<script type="text/javascript" src="{% static 'js/select2.js' %}"></script>
<script >
$(document).ready(function(){
$('.js-data-example-ajax').select2({
minimumInputLength: 2,
multiple:true,
delay: 250,
cache: true,
ajax: {
url: '/tags/search/autocomplete/',
dataType: 'json',
data: function (parms, page) { return { tag_word: parms.term }; },
},
});
});
</script>
here is the server code:
def autocomplete(request):
s = SearchQuerySet(using='autocomplete')
sqs = s.autocomplete(content_auto=request.GET.get('tag_word'))[:5]
suggestions = [ {'text':result.tag_word,
'id':result.tag_word,} for result in sqs]
the_data = json.dumps({
'results': suggestions
})
return HttpResponse(the_data, content_type='application/json')
To select an option each and every result need to have a unique id. Therefore you can add id using following code(processResults).
$('.js-data-example-ajax').select2({
minimumInputLength: 2,
multiple:true,
delay: 250,
cache: true,
ajax: {
url: '/tags/search/autocomplete/',
dataType: 'json',
data: function (parms, page) { return { tag_word: parms.term }; },
processResults: function (data) {
data.results.forEach(function (entry, index) {
entry.id = ''+index; // Better if you can assign a unique value for every entry, something like UUID
});
return data;
},
cache: true
},
});
Its a quick hack. Not sure how you could get along with select2 documentaion. But the following code worked with me in my localhost.
$(document).ready(function(){
$.get("json/select.json",function(data){ //specify your url for json call inside the quotes.
for(var i = 0; i < data.length; i++){
data[i]={id:i,text:data[i].text}
}
$(".js-data-example-ajax").select2({
minimumInputLength: 2,
multiple:true,
delay: 250,
data: data
})
});
}
Its because you got all id's null. change to numbers. Click on the get selected button to see the ids only will be passed.
var data = [{ id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2, text: 'duplicate' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' }];
$(document).ready(function(){
$('.js-data-example-ajax').select2({
minimumInputLength: 2,
multiple:true,
delay: 250,
data: data
});
});
$(".checkoutput").click(function(){
console.log($('.js-data-example-ajax').val());
})
Here is the JSFIDDLE
Further to your final question on Alaksandar's answer, try adding his code like this:
$('.js-data-example-ajax').select2({
minimumInputLength: 2,
multiple:true,
delay: 250,
cache: true,
ajax: {
url: '/tags/search/autocomplete/',
dataType: 'json',
data: function (parms, page) { return { tag_word: parms.term }; },
success: function(results){
for(var i = 0; i < results.length; i++){
results[i] = {id:i,text:results[i].text}
}
}
},
});
I haven't tested any of this. So, if it works, please accept Aleksandar's answer as correct, not this one.
Related
this is html code of my select2 field.
<select data-init-plugin="select2" data-max="4" multiple="" id="mls" name="mls" class="select2 form-control full-width ajax-supported select2-hidden-accessible" data-callback="getAgents" tabindex="-1" aria-hidden="true"></select>
and this is the select2 JavaScript code.
$('.ajax-supported').select2({
ajax: {
dataType: 'json',
multiple: true,
type: "POST",
data: function (term) {
return {
'_token': $('#_token').val(),
name: $(this).attr('name'),
callback: $(this).data('callback'),
q: term.term,
};
},
url: '{{ url('listing-field-ajax-callback') }}',
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.itemName,
id: item.id
}
})
};
},
},
minimumInputLength: 1,
maximumSelectionLength: maximum_selectable_items, // this is where i want 4 from data attribute data-max=4
});
now i want to get data attribute data-max = 4 and i want to use it in my maximumSelectionLength and want to control the number of selected items. how can i get data attribute from the select HTML and use that in my JavaScript?
well i tried this code and it worked.
$.each($('.ajax-supported'), function(k, field) {
var max;
console.log(field);
if($(field).data('max')) {
max = parseInt($(field).data('max'));
}
else {
max = 1;
}
$(field).select2({
ajax: {
dataType: 'json',
multiple: true,
type: "POST",
data: function (term) {
return {
'_token': $('#_token').val(),
name: $(field).attr('name'),
callback: $(field).data('callback'),
q: term.term,
};
},
url: '{{ url('listing-field-ajax-callback') }}',
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.itemName,
id: item.id
}
})
};
},
},
minimumInputLength: 1,
maximumSelectionLength: max,
});
});
I am trying to use js grid for my application. I am trying to populate the grid after ajax request but it do not seem to work as expected.
I am trying with SQL Server as back end and web application is asp.net MVC
This is my code in the html
var table;
var result;
var $j = jQuery.noConflict();
$j(document).ready(function () {
table = $j('#grid').jsGrid({
height: "60%",
width: "50%",
inserting: true,
editing: true,
sorting: true,
paging: true,
autoload: true,
pageSize: 10,
controller: {
loadData: function (filter) {
var d = $j.Deferred();
$j.ajax({
type: "POST",
contentType: "application/json",
url: "#Url.Action("LoadData", "User")",
datatype: "json",
data: filter
#*success: function (data) {
result = data.data;
console.log("result", result);
d.resolve(result)
},
error: function (data) {
window.location.href = '#Url.Action("Error", "Audit")';
}*#
}).done(function (data) {
console.log("response", data);
console.log("data.data", data.data);
d.resolve(data)
});
return d.promise();
},
fields: [
{ name: "LastName", type: "text"},
{ name: "FirstName", type: "text"},
{ name: "Email", type: "email"},
{ name: "PhoneNumber", type: "number"},
{ type: "control" }
]
}
});
});
In Controller I return
''return Json(new { data }, JsonRequestBehavior.AllowGet);''
I expect the json data to bind in the div. But it did not ? Thanks
Ok, so I've had this problem recently.
First off, change your "height" to px, auto, or get rid of it entirely. It's not doing what you think it's doing.
Next, since you have paging, you need to return your data in the following format:
{
data: [{your list here}],
itemsCount: {int}
}
It's barely in the documentation, as it's inline and not very obvious. (Bolding mine.)
loadData is a function returning an array of data or jQuery promise that will be resolved with an array of data (when pageLoading is true instead of object the structure { data: [items], itemsCount: [total items count] } should be returned). Accepts filter parameter including current filter options and paging parameters when
http://js-grid.com/docs/#controller
i'm very desperate!
i have this problem with Bootstrap Typeahead.
HTML Markup:
<div class="form-group">
<label for="">Recipients</label>
<input id="recipients" name="recipients"
autocomplete="off"
class="form-control"
data-role="tagsinput">
</div>
JavaScript:
$('#recipientsContainer').tagsinput({
allowDuplicates: false,
trimValue: true,
confirmKeys: [13, 44],
typeahead: {
hint: true,
highlight: true,
minLength: 4,
limit: 10,
source: function (query) {
$.ajax({
url: "/app/route",
type: 'POST',
dataType: 'JSON',
data: {'query' : query},
success: function(data) {
console.log(data);
return(data);
}
});
},
afterSelect: function() {
this.$element[0].value = '';
}
}
});
After Ajax call I get this array in consolle:
["Justin Demetria +393281893574", "Dylan Alea +393700488191", "Zahir Tatyana +393007841301", "Ryan Veda +393542236060", "Hunter Wanda +393393156943"]
The problem is: I see nothing :( nothing appears. typeahead doesn't work.
In the console, I get this error
bootstrap-tagsinput.js Uncaught TypeError: Cannot read property 'success' of undefined.
How can I fix it?
I'm using Bootstrap 3, last Typeahead js source.
James, now my ajax call is:
$('#recipientsContainer').tagsinput({
allowDuplicates: false,
trimValue: true,
confirmKeys: [13, 44],
typeahead: {
source: function(queryForHints) {
if (queryForHints.length < 4)
return '';
var parameters = {'queryForHints': queryForHints};
jQuery.ajax({
url: "/app/route",
data: parameters,
type: "POST",
dataType: "json",
success: function(data) {
var sourceData = [];
for (var i = 0; i < data.length; i++) {
sourceData.push(data[i].text);
}
return (sourceData);
},
error: function(data) {
console.log("error for xxxxx/xxxxx");
},
async: true
});
}
}
});
But the error persist:
bootstrap-tagsinput.js:331 Uncaught TypeError: Cannot read property 'success' of undefined
the error is on bootstrap-tagsinput.js row 331, and i find:
if ($.isFunction(data.success)) {
// support for Angular callbacks
data.success(processItems);
Can we fix the problem ?
in my humble opinion, the problem is that input - tags can not understand the SUCCESS of an ajax call
For typeahead use Bloodhound to get your data not ajax.
Your code should look like something like this:
var customers = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: '/api/customers?query=%QUERY',
wildcard: '%QUERY'
}
});
$('#customer').typeahead({
minLength: 3,
highlight: true
}, {
name: 'customers',
display: 'name',
source: customers
}).on("typeahead:select", function(e, customer) {
vm.customerId = customer.id;
});
For more Information on Bloodhound:
Bloodhound#github
And here some examples for typeahead: TypeAhead Examples
I need to set default values to the select2 option select which is multiple select and ajax.
Here is the code that i have so far
$("#firstList").select2({
placeholder: "Enter Pincode",
allowClear: true,
cache: true,
initSelection : function (element, callback) {
var data = {id: "IN", text: "INDIA"};
callback(data);
},
ajax: {
url: "../getZipList",
type: "POST",
contentType: "application/json; charset=utf-8",
delay: 250,
data: function (params) {
//console.log(params)
return {
q: params.term, // search term
page: params.page
};
},
processResults: 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 the remote JSON data
return {
results: data.items
};
//console.log(data.it)
},
cache: true
},
escapeMarkup: function (markup) {
return markup;
}, // let our custom formatter work
minimumInputLength: 1,
templateResult: formatRepo, // omitted for brevity, see the source of this page
templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
})
When i try this
initSelection : function (element, callback) {
var data = {id: "IN", text: "INDIA"};
callback(data);
},
The initial values didn't set...
I also tried
var data = [{
id: 'value',
text: 'Text to display'
}];
var tags = $("#firstList option").each(function () {
data.push($(this).val());
});
But the initial values are not setting.
What is the problem i am doing and how can i fix it. Help pls
Here is my code,
var $range = $("#price-slider");
$range.ionRangeSlider({
min: 130,
max: 575,
type: 'double',
prefix: "$",
prettify: false,
hasGrid: true,
onChange : function (data) {
console.log(data);
}
});
Here, it would like to pass the value to the controller.
How should I use Ajax inside the onChange function
And my Ajax is something like this
$.ajax({
url: 'hotelresults',
type: 'POST',
data: {
from: from_val,
to: to_val
},
success: function(data) {
$('.hotel_list').html(data);
}
});
And also here,I dont know how to get the from and to value of price slider..
Someone help me..
Regards
Suganya
For ion range sliders , onChange function takes a parameter say data, which hold range values of slider.
In your case you can use data.from and data.to for range values inside ajax function.
$.ajax({
url: 'hotelresults',
type: 'POST',
data: {
from: data.from,
to: data.to
},
success: function(data) {
$('.hotel_list').html(data);
}
});
You can use ajax request inside the onchange() function and pass slider response into ajax.
Example:
<script type="text/javascript">
var $range = $("#price-slider").val();
$range.ionRangeSlider({
min: 130,
max: 575,
type: 'double',
prefix: "$",
prettify: false,
hasGrid: true,
onChange : function (data) {
//console.log(data);
$.ajax({
url: 'hotelresults',
type: 'POST',
data: "slider_response="+data,
success: function(response) {
$('.hotel_list').html(response);
}
});
}
});
</script>
For getting value of slider you need to use $("#price-slider").val() instead of $("#price-slider")
SCRIPT
var $range = $("#price-slider");
$range.ionRangeSlider({
min: 130,
max: 575,
type: 'double',
prefix: "$",
prettify: false,
hasGrid: true,
onChange : function (data) {
console.log(data.from)
console.log(data.to)
}
});
You can pass the value to AJAX by getting values like
data.to and data.from
DEMO
Thank you soo much..Who were reply me,
It had tried like this way
onChange : function (data) {
var from_num = data.fromNumber;
var to_num =data.toNumber;
$.ajax({
// alert('hai');
url: 'hotelresults',
type: 'POST',
data: {
from: from_num,
to: to_num,
},
success: function(data){
$('.hotel_list').html(data);
}
});
}
And It works for me :) :D