While developing a web app using JavaScript and PHP, I've noticed that I keep rewriting the same ajax calls repeatedly. Is there a way to create a reusable function or variable for these calls, with or without parameters?
I'm fairly new to JavaScript, so please bear with me as I am still learning.
Instead of coding like this:
$("body").on("click", ".all-forms-link", function() {
$.ajax({
url: "forms.php",
type: "post",
data: {formsPage: 1},
success: function(data) {
stage.html(data)
}
});
});
//similar code repeated multiple times
We can approach it in a more organized manner, like shown below:
function loadForms() {
$.ajax({
url: "forms.php",
type: "post",
data: {formsPage: 1},
success: function(data) {
stage.html(data)
}
});
}
body.on("click", ".all-forms-link", function() {
loadForms(); //or something similar
});