I have these two methods that pretty much does the same thing. I would like to improve this by just re-using the other method, something like method overriding in an Object Oriented Programming.
Method 1 Summary: Based on the level, make a post request to a Servlet that returns all the courses for that particular level in JSON format (response). Then load these courses to the combo box ($loadTo). After that pre-select a course provided and show some modal.
function loadCoursesByLevelThenSet(level, course, $loadTo) {
$.post( ... , ... ,
function(response) {
var options = '<option value="">Please select course...</option>';
for (var i = 0; i < response.length; i++) {
...
}
$loadTo.html(options);
$loadTo.val(course);
$('#modal').modal('show');
}).fail(function() {
alert('Something went wrong while loading options for courses. Please try again.');
});
}
Method 2 Summary: Based on the level, make a post request to a Servlet that returns all the courses for that particular level in JSON format (response), then load these courses to the combo box ($loadTo).
function loadCoursesByLevel(level, $loadTo) {
$.post( ... , ... ,
function(response) {
var options = '<option value="">Please select course...</option>';
for (var i = 0; i < response.length; i++) {
...
}
$loadTo.html(options);
}).fail(function() {
alert('Something went wrong while loading options for courses. Please try again.');
});
}
This is what I came up, but it doesn't work correctly:
function loadCoursesByLevelThenSet(level, course, $loadTo) {
if (loadCoursesByLevel(level, $loadTo) === true) {
//after the courses are fully loaded
//select a course
//and show the modal
$loadTo.val(course);
$('#modal').modal('show');
}
}
function loadCoursesByLevel(level, $loadTo) {
$.post( ... , ... ,
function(response) {
var options = '<option value="">Please select course...</option>';
for (var i = 0; i < response.length; i++) {
...
}
$loadTo.html(options);
}).fail(function() {
alert('Something went wrong while loading options for courses. Please try again.');
}).done(function() {
return true;
});
}
What am I doing wrong? Is there any way to achieve this? Thank you.