Guest User

Untitled

a guest
Oct 19th, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. // We use a closure to prevent polluting the global namespace.
  2. var AjaxifyForms = (function($, _) {
  3. "use strict";
  4. // Use strict makes it harder to make stupid mistakes.
  5.  
  6. var AjaxifyForms = {
  7. $form: "",
  8. options: {
  9. formSelector: "form",
  10. successFunction: null
  11. },
  12.  
  13. init: function(options) {
  14. // Initialize
  15. var self = this;
  16. this.options = _.extend(this.options, options);
  17. this.$form = $(options.formSelector);
  18.  
  19. // Bind
  20. this.$form.on("submit", function(e) {
  21. self.interceptSubmit.call(self, e, this);
  22. });
  23. },
  24.  
  25. interceptSubmit: function(e, form) {
  26. // Will interecept any form submissions and turn them into ajax.
  27. e.preventDefault();
  28. var $form = $(form);
  29.  
  30. $.ajax(
  31. $form.attr("action"),
  32. {
  33. type: $form.attr("method"),
  34. data: $form.serialize(),
  35. success: this.options.successFunction
  36. }
  37. );
  38. }
  39. };
  40.  
  41. return AjaxifyForms;
  42. }($, _));
  43.  
  44. // Ajaxify forms is now much more modular and can be reused.
  45. var ajaxifyForms = AjaxifyForms.init({
  46. formSelector: ".some-special-form"
  47. });
Add Comment
Please, Sign In to add comment