From 0225bdb772d1334cc1aa7ab0fc3678df0864df6b Mon Sep 17 00:00:00 2001 From: AlisaLinUwU Date: Sun, 26 Jan 2025 10:42:28 +0500 Subject: Initialize --- src/main/resources/static/js/ajax-form.js | 48 +++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 src/main/resources/static/js/ajax-form.js (limited to 'src/main/resources/static/js/ajax-form.js') diff --git a/src/main/resources/static/js/ajax-form.js b/src/main/resources/static/js/ajax-form.js new file mode 100644 index 0000000..f117a49 --- /dev/null +++ b/src/main/resources/static/js/ajax-form.js @@ -0,0 +1,48 @@ +$(function() { + + // Get the form. + var form = $('#contact-form'); + + // Get the messages div. + var formMessages = $('.ajax-response'); + + // Set up an event listener for the contact form. + $(form).submit(function(e) { + // Stop the browser from submitting the form. + e.preventDefault(); + + // Serialize the form data. + var formData = $(form).serialize(); + + // Submit the form using AJAX. + $.ajax({ + type: 'POST', + url: $(form).attr('action'), + data: formData + }) + .done(function(response) { + // Make sure that the formMessages div has the 'success' class. + $(formMessages).removeClass('error'); + $(formMessages).addClass('success'); + + // Set the message text. + $(formMessages).text(response); + + // Clear the form. + $('#contact-form input,#contact-form textarea').val(''); + }) + .fail(function(data) { + // Make sure that the formMessages div has the 'error' class. + $(formMessages).removeClass('success'); + $(formMessages).addClass('error'); + + // Set the message text. + if (data.responseText !== '') { + $(formMessages).text(data.responseText); + } else { + $(formMessages).text('Oops! An error occured and your message could not be sent.'); + } + }); + }); + +}); -- cgit v1.2.3