Load two ajax request at the same time

680 0 0 0

Last Updated : 2024-04-19 09:14:31

Sometimes, you might need to call two ajax requests at the same time or request, here is a good example to do so

$(".modal-body").on("change", "select[name='subject_id']", function(){
var subject_chosen_id = $(this).val();
var field_name = $(this).attr("name");

var url="{{url('admin/getModulesAsSelect')}}/"+subject_chosen_id+"/0/related_to_module_id";
var unitsUrl="{{url('admin/getUnitsAsSelect')}}/"+subject_chosen_id+"/0/related_to_unit_id";

var returnedModules;
var returnedUnits;
$.when(
$.ajax({
url : url,
method : 'get',
data : '', // The form with the file inputs.
processData: false, // tell jQuery not to process the data
async : false,
cache : false,
enctype : 'multipart/form-data',
headers : { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
dataType : 'text',
beforeSend : function () { },
success : function (msg) {
// $("select[name='related_to_module_id']").replaceWith(msg);
returnedModules = msg;

}
}),

$.ajax({
url : unitsUrl,
method : 'get',
data : '', // The form with the file inputs.
processData: false, // tell jQuery not to process the data
async : false,
cache : false,
enctype : 'multipart/form-data',
headers : { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
dataType : 'text',
beforeSend : function () { },
success : function (msg) {
// $("select[name='related_to_unit_id']").replaceWith(msg);
// console.log(msg)
returnedUnits = msg;
}
})

).then(function() {
$("select[name='related_to_module_id']").replaceWith(returnedModules);
$("select[name='related_to_unit_id']").replaceWith(returnedUnits);
});
});

Mohammed Anwar

Mohammed Anwar

Experienced technical lead PHP, MySQL and Laravel Developer for 15+ years, with proven ability to develop and create high-quality and optimized web applications. Great ability to build and optimize database design, schema and queries. Versed programing trainer and instructor delivering web courses and helping others to get into the field in a timely manner. Fast and eager learner for new technologies .