Ajax form handling
Thu Mar 16 2023 19:48:35 GMT+0000 (Coordinated Universal Time)
Saved by @khalidlogi #php
// A JavaScript module for submitting forms via AJAX // This module depends on jQuery and the jQuery Form Plugin var FormSubmission = { // Class to add to elements with form errors formErrorClass: 'form-error', // Adds form errors to the DOM appendFormErrors: function(data, form) { // Loop through the error data object for (var key in data) { // Create a new span element for the error message var error = $(document.createElement('span')).attr('class', FormSubmission.formErrorClass).text(data[key]); // Insert the error message before the input field with the corresponding name form.find("input[name='" + key + "']").before(error); } }, // Hides the closest modal element to the given form closeModal: function(form) { form.closest('.modal').modal('hide'); }, // Handles the response from the form submission postFormSubmission: function(form, isModal, data) { // Remove any existing form errors FormSubmission.removeFormErrors(form); // If the form was submitted successfully if (data['success'] == true) { // Reset the form and close the modal if it's a modal form FormSubmission.resetForm(form, isModal); } else { // Append the form errors to the DOM FormSubmission.appendFormErrors(data['errors'], form); } }, // Removes form errors from the DOM removeFormErrors: function(form) { form.find('.' + FormSubmission.formErrorClass).remove(); }, // Calls resetForm with isModal set to false resetForm: function(form) { FormSubmission.resetForm(form, false); }, // Resets the form and closes the modal if it's a modal form resetForm: function(form, isModal) { // Remove any existing form errors FormSubmission.removeFormErrors(form); // Reset the form form[0].reset(); // If it's a modal form, close the modal if (isModal == true) { FormSubmission.closeModal(form); } }, // Calls submitForm with isModal set to false submitForm: function(form) { FormSubmission.submitForm(form, false); }, // Submits the form via AJAX submitForm: function(form, isModal) { var url = form.attr('action'); // Make an AJAX request to the form's action URL $.ajax({ method: "POST", url: url, data: form.serialize(), myForm: form, isModal: isModal, // Handle the response from the server success: function(data) { FormSubmission.postFormSubmission($(this).myForm, $(this).isModal, data); }, // Handle any errors error: function(jqXHR, textStatus, errorThrown) { console.log(textStatus, errorThrown); } }); }, // Submits the form via AJAX with support for file uploads submitFormWithFiles: function(form, isModal) { var url = form.attr('action'); // Make an AJAX request to the form's action URL with support for file uploads form.ajaxSubmit({ method: 'POST', url: url, myForm: form, isModal: isModal, // Handle the response from the server success: function(data) { FormSubmission.postFormSubmission($(this).myForm, $(this).isModal, data); }, //
Comments