Ajax function ( with nesting )
function open_appointment(id)
{
save_method = 'open_appointment';
$('#form_open_appointment')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('ReceptionistController/ajax_edit_appointment')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$.ajax({
url : "<?php echo site_url('DoctorController/ajax_edit_patient')?>/" +data.ap_patient,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="pt_name"]').val(data.pt_name);
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Failed');
}
});
$('#modal_open_appointment').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Open Appointment'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
i want to use one ajax call into another . i have written the above code but its not working (when nested ), and give show "Failed" . There is problem in nesting of ajax call function
the syntax is looking good,but first, check the outer ajax request that it's working correctly and return the data.ap_patient correctly or not. after that call inner ajax request. and also check inspect elements that request is going to correct action methods or not.
You could use promises like below
Code is untested...
For reference: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
var getAppointment = function() {
return new Promise(function(resolve, reject) {
$.ajax({
url : "<?php echo site_url('ReceptionistController/ajax_edit_appointment')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
resolve(data);
},
error: function (jqXHR, textStatus, errorThrown)
{
reject('Error get data from ajax');
}
});
})
}
var editPatient = function(data) {
return new Promise(function(resolve, reject) {
$.ajax({
url : "<?php echo site_url('DoctorController/ajax_edit_patient')?>/" +data.ap_patient,
type: "GET",
dataType: "JSON",
success: function(data)
{
resolve(data);
},
error: function (jqXHR, textStatus, errorThrown)
{
reject('Failed');
}
});
}
}
getAppointment()
.then(function(data) {
return editPatient(data)
})
.then(function(data) {
$('[name="pt_name"]').val(data.pt_name);
})
.catch(function(error) {
console.log(error)
));