I am trying to minimalise the number of similar functions I am adding to my code by writing one general function in jQuery. When it comes to form submissions, the top section of AJAX code is more or less the same for all my applications, however what happens in the success section can vary greatly between applications.
function general_submit_form(url, query, button, form) {
$(document).on("click", button, function() {
var data = $(this).closest('form').serialize();
var url = url + '?' + query;
$.ajax({
type: 'POST',
data: data,
url: url,
success: function(data) {
console.log(data);
if (data == 0) {
alert("Required parameters are empty!");
} else if (data == 1) {
alert("Storage Space Added");
//fetch_storage_spaces();
$(form)[0].reset();
$(".custom_input").closest('tr').addClass('hidden');
fetch_storage_names("fetch_storage_names", "#storage_names");
fetch_all_storage_submit_forms();
} else if (data == 2) {
alert("Storage name or serial taken");
}
}
});
});
}
This function is an example of a general function I am trying to write. Is there any way I could change what happens inside the success section of the code outside the function? Specifically inside the data == 1
if statement?
Thank you!
2
Answers
To achieve this you could provide a function as an argument to the
general_submit_form()
call which you can execute under the right condition, something like this:You can pass success function as parameter too.