I have two dropdown/select widgets on a form. I am trying to set the options of the second select through an ajax call in jQuery, and then execute further code. The ajax call is successful and correctly sets the second select options, but it seems the code after the ajax call is not executed at all. How to correct this?
view:
{{extend 'layout.html'}}`
<h1>{{=title}} /This is the library/edit_user.html template</h1>
{{=grid}}
<script>
jQuery("#no_table_region_id").change(function(){
region_id = $(this).val();
branch_id = jQuery('#no_table_branch_id').val();
ajax("{{=URL('library', 'branches')}}" '?region_id=' region_id, [], 'no_table_branch_id');
jQuery('#no_table_branch_id').val(branch_id); # this does not execute
});
jQuery(document).ready(function(){
// todo: solve the unsettable branch_id
jQuery("#no_table_region_id").change();
});
</script>
controller:
def branches():
if request.vars.region_id:
branches = db(db.branch.region_id==request.vars.region_id).select(db.branch.ALL)
ops1 = ['<option value=""></option>']
ops = ops1 [f"<option value={i['id']}>{i['branch_name']}</option>" for i in branches]
else:
ops = ''
return ops
CodePudding user response:
The line after the ajax
call is executed. However, because the ajax
function makes an asynchronous call, its results are not returned and used to update the DOM until after that next line has already run.
Note, the third argument to ajax
can be a callback function that takes the result of the Ajax call, so you can use that method to update the options and then set the value:
ajax(
"{{=URL('library', 'branches')}}" '?region_id=' region_id,
[],
options => {
jQuery('#no_table_branch_id').html(options);
jQuery('#no_table_branch_id').val(branch_id);
}
);