jQuery val() not working on option appended through ajax - javascript

I have a jQuery/Ajax function that is appending 2 <option>s to a <select>.
function addOption() {
var author = $("#authors").val();
$('#books').empty();
$('#books').html('<option value="">Please Select</option>');
$.ajax({
type: "post",
url: "books.php",
data: { author:author },
success: function(response){
$('#books').append(response);
}
});
}
response comes back as -
<option value="bookA">Book A</option>
<option value="bookB">Book B</option>
and now books is -
<select id="books">
<option value="">Please Select</option>
<option value="bookA">Book A</option>
<option value="bookB">Book B</option>
</select>
This works great.
Now I want to set the selected option using .val() after calling addOption() -
$('#authors').change( function(){
addOption();
$('#books').val('bookB');
});
This does not make Book B selected.
If I hard code the .append() it works -
function addOption() {
var author = $("#author").val();
$('#books').empty();
$('#books').html('<option value="">Please Select</option>');
$('#books').append('<option value="bookA">Book A</option>\n<option value="bookB">Book B</option>);
}
$('#authors').change( function(){
addOption();
$('#books').val('bookB');
});
Is there a reason why my option(s) appended in the .ajax function cannot be selected using .val(), put it can if I append them directly?

That's because the AJAX call is asynchronous, so when you try to select the options, it hasn't been added to the select yet.
Use a callback in the function, so that you can do something when the response has arrived:
function addOption(callback) {
var author = $("#authors").val();
$('#books').empty();
$('#books').html('<option value="">Please Select</option>');
$.ajax({
type: "post",
url: "books.php",
data: { author:author },
success: function(response){
$('#books').append(response);
callback();
}
});
}
Usage:
$('#authors').change( function(){
addOption(function(){
$('#dropdownB').val('bookB');
});
});

AJAX is asynchronous, meaning that when you call the addOption() method, it might (and probably will) return before the Ajax call has actually been made, so you are calling $('#dropdownB').val('bookB'); before the Ajax callback has been triggered to append the options.
Try putting the $('#dropdownB').val('bookB'); into the success callback of the ajax call and you should see it working.

Ajax is asynchronous, when you set the value, there is no option with that value, you can put your code in your success callback.
success: function(response){
$('#books').append(response);
// ...
}
Or set that value of async property of your Ajax request to false;

This is because ajax is asynchronous. That is, by the time it returns and appends the new options to the select list, the browser engine has already continued and tried to set the value (which wasn't yet added). Try moving the value setting logic to work as part of the ajax response.

1) You should put $('#dropdownB').val('bookB'); inside the success-event of your ajax-call, because AJAX is asynchronous and your request may not be done when you try to change the selected item, so there is no item to select yet.
2) You append to #books but change the selected item of #dropdownB. Those are two different ids and hence two different DOM elements.

Related

bootstrap-select doesn't populate from AJAX call

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>`);
});

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");

Is this a proper way of using AJAX with jQuery and PHP?

I need some help. I'm going use AJAX (for the first time) and I'd like you to tell me whether the way I am going to show you is optimal.
Let's say that I have a select element.
<select class="update-db" data-id="25" data-original-value="2">
<option value="1">Yellow</option>
<option value="2" selected="selected">Red</option>
<option value="3">Blue</option>
</select>
So here is what I do:
$(document).on('change', 'select.update-db', function() {
// Get needed data
var select = $(this);
var id = select.attr('data-id');
var originalValue = select.attr('data-original-value');
var newValue = select.val();
// Perform the request
$.ajax({
method: 'POST',
url: 'update-db.php',
data: { id: id, 'original-value': originalValue, 'new-value': newValue }
});
// Then, if everything is okay, change the "original value" of the select element
// so that we can perform the updating operation again without having to refresh the page
.done(function() {
select.attr('data-original-value', newValue);
});
});
Then, on the other side, a PHP script validates everything and updates the database.
Is this the correct way of using AJAX? I feel it's not. What am I doing wrong?

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