The chain of Ajax calls can be set programmatically, instead of being "hardcoded" as in your code. The next snippet shows a possible approach.
However, as Piotr pointed out, you should study your application a bit more to determine whether that is a good solution.
// First generate an array with all the ajax calls than need to be done, in order.
var ajaxCalls = [
// First ajax
function(){
return $.ajax({
type : 'POST',
url : 'php echo $vars['url']?>learn/pages/syllabus/saveitems.php',
datatype : 'html',
data : {subtask:subTask,lessonid:lesson_id,theSubModID:video_id,userid:user_id,prodid:course_id,taskname:taskName}
});
},
// Second ajax
function(data){
return $.ajax({
type : 'POST',
url : 'php echo $vars['url']?>learn/pages/syllabus/saveitems.php',
datatype : 'html',
data : {subtask:subTask,lessonid:lesson_id,userid:user_id,prodid:course_id,taskname:taskName}
});
},
...
// Last function doesn't need to return a promise
function(data){
$(course_box).replaceWith(data);
$(".accordion").accordion({
active: false,
collapsible: true,
heightStyle: "content"
});
}
];
// Every time you run an ajax, you want to set it up so that the next
// ajax will be called as a response. Let's do a function for that:
function callAjax(var index){
var thisAjax = ajaxCalls[index];
// Run the ajax
var promise = thisAjax();
// Set up next one if necessary.
var isLastAjax = (index === (ajaxCalls.length - 1));
if(!isLastAjax){
promise.done(function(){
callAjax(index + 1);
});
}
}
// Call the first one
callAjax(0);
manpreet
Best Answer
2 years ago
I have one button on clicking I need multiple things need to be done, so I went for AJAX and PHP: