How to refresh select option list after AJAX response - javascript

I use fastSelect plugin http://dbrekalo.github.io/fastselect/
I have input tag, when change value i do a call ajax to php server.
My problem is that When I inspect the item and I look in the options, I see the data I just added, but in the browser it does not display, sorry for the quality of my English
any help please ?
Enclosed my code
<select id="Recherche_log_commune" name="Recherche[log_commune][]" class="multipleSelectDepCom" multiple="multiple">
<optgroup label="Communes">
</optgroup>
</select>
<script> $('.multipleSelectDepCom').fastselect({maxItems: 10,noResultsText: 'Pas de résultat'}); </script>
<script>
$("#leftBlockDashboard .fstQueryInput").on("change paste keyup", function(event) {
event.preventDefault();
getCommuneAndDepartement($(this).val());
});
function getCommuneAndDepartement(expression) {
var dataString = {expression: expression};
$.ajax({
url: '{{path('get_commune_departement')}}',
type: "POST",
data: dataString,
success: function(data){
$("#Recherche_log_commune").find('optgroup[label="Communes"]').empty();
$.each(data, function(){
var option = '<option value="'+ this.com_id +'">'+ this.com_libelle +'</option>';
$("#Recherche_log_commune").find('optgroup[label="Communes"]').append(option);
});
$('.multipleSelectDepCom').fastselect({
maxItems: 10,
noResultsText: 'Pas de résultat',
});
}
})
}
</script>

ok solved , very rude but works ... on ajax callback here is what i do:
1) get a reference to original node ...
in my case it is
var cc = $('#categories');
2) check if .fstElement exists
var fsexist = $(".fstElement").length > 0;
3) if exists remove it and reappend the original node
if (fsexist) {
$('.fstElement').remove();
$('#categories_div').append(cc);
}
4) reinit fastselect
$('#categories').fastselect({maxItems: 10,
noResultsText: 'Choose categories'});

You will need to reattach the control after the options are loaded:
$('.selector').fastselect();
Even more complicated (to keep the selected value):
$('.selector').fastselect({
onItemSelect: function($item, itemModel) {
//load your stuff
$('.selector').fastselect();
}
});

You Will need to refresh the select2 after ajax call like this.
setTimeout(function(){
$('#select2_id').fastselect();
},500);

Related

Problems with jQuery onchange on ios

I'm having problems with the jQuery onchange event not working in Safari on my iPhone.
This is where the onchange is:
//Detects change in location and updates with location name and address
$('#location').on('change', function () {
var serviceId = $("#location").val();
$.ajax({
type: "get",
url: 'utilities/fetchdata?fetch=locationbyid&location=' + serviceId + '',
success: function (data) {
var locationData = JSON.parse(data);
document.getElementById("location-name").innerHTML = locationData.name;
document.getElementById("location-address1").innerHTML = locationData.address;
//Fetch servies offered by that location
$.ajax({
type: "get",
url: 'utilities/fetchdata?fetch=services&location=' + serviceId + '',
success: function (data) {
console.log(data);
var newOptions = JSON.parse(data);
var $el = $("#service");
$el.empty(); // remove old options
$.each(newOptions, function(key,value) {
$el.append($("<option></option>")
.attr("value", value).text(key));
});
}
});
}
});
});
This is what it is listening on:
<select name="location" class="form-control" id="location">
<option disabled selected>-- Velg Lokasjon --</option>
<?php
//Fetch locations
if (! $locations = $locationData->fetchHTMLINPUT()) {
echo $locations;
} else {
echo "<option disabled>Systemfeil oppsto</option>";
}
?>
</select>
What I need it to do is fire the event consistently as this is where it fetches the next step for the user to follow.
Expected behaviour:
Fetch the next input fields for use in the select
What I think is weird is that it works in Chrome on my desktop as well as Edge.
Could anyone point me to a workaround for use on mobile?
Okay,
I kinda figured it out. Seems like mobile iOS browsers can't refresh the contents of a select after the HTML has been rendered, but changing the HTML using f.ex $('#service').html(data); works like a charm, though the HTML has to be generated server side.

Add HTML code triggered by selection changed

I have a simple select into my HTML code (a dropdown menu).
HTML
<select name="razza" onchange="razzaChanged()">
<?php while ($row = gdrcd_query($result, 'fetch')){ ?>
<option value="<?php echo $row['id_razza']; ?>" <?php if(gdrcd_filter('get',$_POST['razza'])==$row['id_razza']){ echo 'SELECTED'; } ?>>
<?php echo gdrcd_filter('out',$row['nome_razza']); ?>
</option>
<?php } ?>
JavaScript
<script>
function razzaChanged()
{
alert("I am an alert box!");
}
</script>
When the selection of the dropdown is chosen, I have to add some information below the dropdown. The information I have to add is a bit complex and pretty formatted (I need to do some query to retrieve data and then add text and another dropdown after the info).
How can I achieve this? I can register via JavaScript that the selection changed but then I don't know how to go further.
You could use ajax methods. Get value from select using oninput/onchange, use that value as data in ajax request. If request is successful then show server's response in a container where ever you want.
HTML
<select name="razza" id="razza">
<option value="1">Some Option</option>
<option value="2">Another Option</option>
<!-- Use your loop here and remove these options -->
</select>
Javascript
$("#razza").on('input change',function(){
var value = $(this).val();
// Ajax Request
$.ajax({
type: 'post', // you can also use 'get'
url: '/link/to/your/server/file',
data: {
key: value // use key required by backend
},
success: function(response) {
$('#your-container-div-id').html(response);
}
});
});
Please note that I have used code without 'onchange' attribute, as this is better. Feel free to ask...
There are few ways to achieve this. One would be to use what jquery library offers.
Here are just some very rough steps of how one could do it:
In your razzaChanged() function establish which value is selected:
function razzaChanged()
{
var val = $('select[name="razza"] option:selected').val();
// step 2 here
}
Now use this value to fetch data from the server with the help of AJAX:
$.ajax({
type: "GET",
url: '/your-url-to-call',
data: 'your_value=' + val,
success: function(data) {
// step 3 here
}
});
Now having data from server (i.e. json format) build your new select dropdown, i.e.:
var newSelect = $('<select>').appendTo('body');
$(data).each(function() {
newSelect.append($("<option>").attr('value', this.some_property).text(this.some_text));
});
It's definitely not a ready-to-use code as you would have to make sure you return properly formatted data on server side or change the code accordingly. Also
make sure jquery library is loaded and the code is wrapped with its ready function (easy to find example on internet).
Hope this helps.
You will need to do an AJAX POST or GET request to retrieve data from your database and you will need to use document.createElement("elementtype"); to create an element to add to your page.
With jQuery, your AJAX would look something like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$.ajax({
type: "POST",//can be GET or POST
url: "yoururl",
statusCode: {
404: function() {
alert( "page not found" );
},
data: {key: value},//you can have multiple keys and values
success: function(res){
//add elements to the page
$('#yourelememntid').html(res.someattribute);
}
}).done(function() {
//AJAX request finished
});
</script>

execute command to new loaded content from ajax jquery

I got some problem with jquery.
<select class='my-select' id='exist_select'></select>
<div id='target'></div>
<script>
$.ajax({
type : 'GET',
url : "<?php echo site_url().'rekap/get_akun?id_subkom=' ?>"+id_subkom,
dataType : 'json',
success: function(data){
var select = '';
for (var key in data){
select = '<select class="my-select" id="select'+data[key]+'"></select>';
}
$('div#target').html(select);
$('.my-select').append($('<option>', {
value: 100,
text: 'Added option',
}))
})
})
</script>
The selects was successfully loaded. As you see, I tried to make HTML selects. Then append spesific option manually for each select.
Unlucky, It doesn't work. But it works on #exist_select.
I have no idea. Please help me.
First wrap your code in a document ready statement, second your loop only gets the first element, you need to use concatenation to append the rest,3th you can append the option directly in the select:
$(function(){
$.ajax({
type : 'GET',
url : "<?php echo site_url().'rekap/get_akun?id_subkom=' ?>"+id_subkom,
dataType : 'json',
success: function(data){
var select = '';
for (var key in data){
select += '<select class="my-select" id="select'+data[key]+'"><option value="100">Added option</option></select>';
}
$('div#target').html(select);
})
})
})
Event listeners can only be attached to elements that are in the DOM, not elements that don't exist at the time.
For dynamically created elements, you need to use the .on function:
$('body').on('change', '.my-select', function(){
alert('here');
});

update session and refresh page with ajax/jquery

I need help with a script that according to 2 parameters updated me a $ _SESSION variable and then refresh the page. One of these parameters comes from a select and the other according to a select class "active".
Here's my code:
<div class="simple-drop-down">
<select id="select-order">
<option>Price</option>
<option>Category</option>
<option>A - Z</option>
</select>
And my jquery function like this:
function order_visual() {
var type_order = $('#loader-wrapper').val();
var arrow_order = $( "#select-arrow" ).hasClass( "active" );
$.ajax({
url: "visual.php?order="+type_order="&"+arrow_order,
type: "post",
data: {},
success: function(data){
location.reload();
}
});
});
And then the PHP is a simple script that manages the $_SESSION.

AJAXed Select form element defaults to first option even if changed

Updated: The DOM is creating a second select instance of #dockhouse-reservation-vessel. It's overriding the first which is the "real" one with the right value
The events are triggered, data retrieved and replaced. #dockhouse-reservation-vessel's value shows in an alert() but not in $_POST. If I comment out the second block of jQuery, the problematic select's value is remembered correctly.
$('form').delegate('#dockhouse-reservation-owner','change', function(){
$.ajax({
url: '/dockhouse/ajax/vessels/' + $(this).val() + '/',
success: function(data){
$('#dockhouse-reservation-vessel').empty();
$('#dockhouse-reservation-vessel').append(data);
}
});
});
data represents option elements:
<!DOCTYPE html>
<option value="">Choose a vessel</option>
<option value="1744">Stinkpot</option>
<option value="1726">Poopy Snoop</option>
<option value="1704">Catchup</option>
The data below represents a table.
$('form').delegate('#dockhouse-reservation-vessel','change',function(){
$.ajax({
url: '/dockhouse/ajax/locations-by-reservation-criteria/' + $(this).val() + '/',
success: function(data){
$('#assign-location').empty();
$('#assign-location').append(data);
}
});
});
Any ideas?
As you are removing and reinserting the whole select box, the state is removed.
You can save the old value in a temp variable and apply it in the callback:
$('form').delegate('#dockhouse-reservation-vessel','change',function(){
// save the value
var oldValue = $(this).val();
$.ajax({
url: '/dockhouse/ajax/locations-by-reservation-criteria/' + oldValue + '/',
success: function(data){
$('#assign-location').empty();
$('#assign-location').append(data);
// select the old value
$('#dockhouse-reservation-vessel').val(oldValue);
}
});
});
WOW, stupid mistake. There was a select field with the same name being pulled in with the table ajax response. Walks away in shame...

Categories

Resources