Skip to content

Instantly share code, notes, and snippets.

@nepkto
Created August 18, 2023 20:53
Show Gist options
  • Save nepkto/c180bc88be79b9f1c172dbe6a320c3bb to your computer and use it in GitHub Desktop.
Save nepkto/c180bc88be79b9f1c172dbe6a320c3bb to your computer and use it in GitHub Desktop.
Reusable Ajax Request
<!-- Include jQuery library -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
function handleFormSubmit(formSelector, buttonText, successCallback, errorCallback) {
$(document).ready(function() {
$(formSelector).submit(function(event) {
event.preventDefault();
var form = $(this);
var method = form.attr("method");
var submitButton = form.find('[type="submit"]');
var formData;
// Store the original button text
var originalButtonText = submitButton.html();
// Disable the submit button and show loader
submitButton.prop("disabled", true);
submitButton.html('<span class="loader"></span> Loading...');
if (form.find('input[type="file"]').length > 0) {
formData = new FormData(form[0]); // Use FormData for forms with files
} else {
formData = form.serialize(); // Use normal serialization for forms without files
}
$.ajax({
url: form.attr("action"),
data: formData,
type: method,
contentType: false, // Required for file uploads
processData: false, // Required for file uploads
success: function(data) {
// Enable the submit button and restore text
submitButton.prop("disabled", false);
submitButton.html(originalButtonText);
if (typeof successCallback === "function") {
successCallback(data);
}
},
error: function(err) {
// Enable the submit button and restore text
submitButton.prop("disabled", false);
submitButton.html(originalButtonText);
if (typeof errorCallback === "function") {
errorCallback(err);
}
}
});
});
});
}
// Usage example on different forms (with or without file inputs)
handleFormSubmit(
"#form1",
"Submit", // Original button text
function(data) {
// Success callback logic for form1
console.log("Form 1 success:", data);
},
function(err) {
// Error callback logic for form1
console.error("Form 1 error:", err);
}
);
handleFormSubmit(
"#form2",
"Send", // Original button text
function(data) {
// Success callback logic for form2
console.log("Form 2 success:", data);
},
function(err) {
// Error callback logic for form2
console.error("Form 2 error:", err);
}
);
// You can define more instances for different forms or pages
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment