bootstrap-select doesn't populate from AJAX call - javascript

I am trying to populate a bootstrap-select control using the following AJAX call:
function loadCategories() {
$.ajax({
url: '../handlers/getcategorylist.ashx',
data: null,
method: 'post',
dataType: 'json',
success: function (data) {
alert(JSON.stringify(data));
$('#ddlCategories').html(JSON.stringify(data));
$('#ddlCategories').selectpicker('refresh');
},
error: function (e) {
console.log(e.responseText);
}
});
}
The HTML for the bootstrap-select is as follows:
<div class="row mb-2">
<div class="col-lg-10 offset-lg-1">
<select id="ddlCategories" name="ddlCategories" data-width="25%" class="form-control selectpicker">
<option value="select">Select From The List</option>
</select>
</div>
</div>
The AJAX call executes and is successful. Using JSON.stringify() I get the following data back (shown in an alert):
For whatever reason, the bootstrap-select doesn't populate. It displays empty. What am I missing here?

Hi it seems like you're setting the inner HTML of your select element to a array of objects. You probably have to .forEach() through all the objects inside of your response array and append them to the select element (like described in the following StackOverflow answer. If you'd also like to remove existing content from the select element consider setting the html to blank.
So something along the lines of:
data.forEach(entry => {
$('#ddlCategories').append(`<option value=${entry['ID']}> ${entry['Name']} </option>`);
});

Related

value of an option appended to a select ends with " before the fetched value ends

I'm fetching some data using ajax from my database, the problem is when I append an option to a select with a value containing these data, the append ends the first word with " thus the rest is left outside the value tag.
Here's the empty select:
<select name="Sender" id="SenderNames" class="form-control" style="width: 100%;"></select>
This is the jQuery code:
$('#SenderSelect').on('change', function() {
$.ajax({
type: "POST",
url: 'operations/inner-operations/getNamesByService.php',
data: { action :"getService", "serviceName" : $("#SenderSelect option:selected").val() },
success: function(data) {
var responseObj = jQuery.parseJSON(data);
console.log(responseObj);
$.each(responseObj, function(i, value) {
$("#SenderNames").append('<option value='+value+'>'+value+'</option>');
});
}
});
});
The appended option should look like this:
<option value="First Second">First Second</option>
However, it is appended like this:
<option value="First" second="">First Second</option>
I just realised that I'm not closing the string properly. The append should be like this:
$("#SenderNames").append('<option value="'+value+'">'+value+'</option>');
the value tag must be wrapped by "".

How can I call an attrib same as value on javascript?

Option:
<select class="form-control se" style="width: 155px;" onchange="showOptions(this)" id="tripSelect">
<option class="dd" id="opt{{$z}}" value="{{$blah}}" data-egid="{{$optionID}}">{{$event->trip_name}}</option>
</select>
I'm using this console:
function showOptions(s) {
console.log(s[s.selectedIndex].getAttribute("data-egid"));
}
and it's working but when I used the same
var trip_id = $('#tripSelect :selected').getAttribute("data-egid"));
//---------------------
$.ajax({
type: "GET",
url: "{{blah blah}}",
data: {
event_group_id: trip_id,
},
//...
});
It's now telling me that getAttribute is not a function
getAttribute() is a function on a regular DOMElement, not some jQuery-wrapped object.
You didn't show us the relevant code, but somewhere in your top sample, if that's working, s[s.selectedIndex] is a regular DOMElement.
In your lower code, $('#tripSelect :selected') returns a jQuery-wrapped array of elements, which have different functions.
If you wanted that first element, you could have probably done something like:
$('#tripSelect :selected')[0].getAttribute("data-egid");

Jquery Chosen Ajax call not rendering the options

I am using Jquery 1.6.4 and chosen 1.4.1. I am facing issue while rendering the options from AJAX. Following is my code.
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery(".chzn").data("placeholder","Select Frameworks...").chosen();
jQuery("#item").chosen().change(function(e, params){
values = jQuery("#item").chosen().val();
$('#item_selected').val(values);
});
});
$('#customer').click(function() {
var url = "ajax_common.php?action=getItem&companyid=1";
$.ajax({
type: 'GET',
url: url,
dataType: 'html',
success: function(data){
$("#item option").remove();
$("#item").append(data);
$("#item").trigger("liszt:updated");
}
});
</script>
<select class="chzn inpt-fld" multiple="true" name="item" id="item" style="width: 96%">
</select>
But the value is not appending in the multi-select drop-down?
The problem seem came from the way you output ajax response. You can not append options in the select tag dynamically because it is not belong to the current select. Meaning this select can not detect the options that previously not exist (as hard code).
You should include select and option together in ajax_common.php and render in div as innerHtml.
// inside ajax_commond.php :
<select class="chzn inpt-fld" multiple="true" name="item" style="width: 96%">
<option> xxxx </option>
</select>
// render the ajax response in :
<div id="item"></div>

How do you submit the selected value in a dropdown via ajax in Django

Am a little bit newbie to django ajax so my question might be an easy thing for experts.
I have a select option dropdown where i want when the user selects a value from dropdown, the value is submitted via ajax so that i can run querysets in the django backend using the selected value.
I can somehow figure out to do this in the backend but need a little help with how to submit this value in the front end by ajax.
here is the dropdown code,just basic html,
<select>
<option>joshua</option>
<option>peter</option>
<option>james</option>
<option>pawine</option>
<option>flonah</option>
</select>
I want an ajax function that will send the selected value to server so that i can use it to run a queryset in the django backend and return the result to ajax success function appropriately.
Thanks in adavnce
Here's an example using JQuery that places an event handler on the select widget that will call your Django view when the user makes a selection. In this example the selected name is being appended to the URL so that Django can grab it with the following regex in urls.py:
url(r'^path_to_app/(?P<name>\w+)$', 'app.views.function'),
Here's an example:
<select id="chooseme">
<option>--select a name--</option>
<option>joshua</option>
<option>peter</option>
<option>james</option>
<option>pawine</option>
<option>flonah</option>
</select>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function() {
$('#chooseme').change(function(){
var name = document.getElementById("chooseme").value;
$.get('/path_to_app/' + name, function(data){
// do something here with a return value data, if desired
});
});
});
</script>
Check that:
<select id="select_form">
<option>joshua</option>
<option>peter</option>
<option>james</option>
<option>pawine</option>
<option>flonah</option>
</select>
var name = $('#select_form').find(":selected").text();
var url = 'your_url_here'+userName+'/';
$.get(url, function(data)
{
//do something with data
})
I tried like this for the following select dropdown:
<select id="select_dropdown">
<option value='joshua'>joshua</option>
<option value='peter'>peter</option>
....
....
</select>
<script>
$(document).ready(function(){
$('#select_dropdown').change(function(){
var e = document.getElementById("select_dropdown");
var value = e.options[e.selectedIndex].value;
$.ajax({
url: "your-url",
type: "post",
data: value,
success: function(data) {
console.log(data);
}});
});
</script>

Using jquery ajax, datatype:html and I need to get part of coming data

Here is my js function;
function getCountryRegions() {
var postData = "id="+$("#selectedCountryId").val();
$.ajax({
url:"/region",
data: postData,
dataType:"html",
type:"POST",
success: function(data){
$("#selRegion2").html(data);
$("#selRegion")== $("#selRegion2").html($(data).find("#selRegion"));
}});}
The 'data' come exactly like this;
<label>Bölge</label>
<select name="selRegion" id="selRegion">
<option value="0" selected="selected" >-- tümü</option>
<option value="4140104">Adana</option>
<option value="4141360">Adrasan</option>
<option value="4137856">Afyon</option>
</select>"
My aim is to get selRegion element and pass it to an Array of Objects. Each object has value and text
I tried this line to make it;
$("#selRegion")== $("#selRegion2").html($(data).find("#selRegion"));
If your data is coming through in perfect HTML format, one trick you can use is this:
var $data = $("<data />").html(data);
Then you can get elements from it like:
$data.find("select").each(function(i) { /* DO WORK */ });
What this does is create a jQuery Element object Tagged <data>. Thus you're able to act upon it like any other jQuery element like $("div") or $("select")

Categories