ajax-form.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. $(function() {
  2. // Get the form.
  3. var form = $('#contact-form');
  4. // Get the messages div.
  5. var formMessages = $('.ajax-response');
  6. // Set up an event listener for the contact form.
  7. $(form).submit(function(e) {
  8. // Stop the browser from submitting the form.
  9. e.preventDefault();
  10. // Serialize the form data.
  11. var formData = $(form).serialize();
  12. // Submit the form using AJAX.
  13. $.ajax({
  14. type: 'POST',
  15. url: $(form).attr('action'),
  16. data: formData
  17. })
  18. .done(function(response) {
  19. // Make sure that the formMessages div has the 'success' class.
  20. $(formMessages).removeClass('error');
  21. $(formMessages).addClass('success');
  22. // Set the message text.
  23. $(formMessages).text(response);
  24. // Clear the form.
  25. $('#contact-form input,#contact-form textarea').val('');
  26. })
  27. .fail(function(data) {
  28. // Make sure that the formMessages div has the 'error' class.
  29. $(formMessages).removeClass('success');
  30. $(formMessages).addClass('error');
  31. // Set the message text.
  32. if (data.responseText !== '') {
  33. $(formMessages).text(data.responseText);
  34. } else {
  35. $(formMessages).text('Oops! An error occured and your message could not be sent.');
  36. }
  37. });
  38. });
  39. });