Advertisement
mdunbavan

ajax post form plugin

Aug 6th, 2013
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.  * jQuery FormSubmit: Effortless AJAX-based form submission
  3.  *
  4.  * Copyright Cory LaViska for A Beautiful Site, LLC. (http://www.abeautifulsite.net/)
  5.  *
  6.  * Dual-licensed under the MIT and GPL Version 2 licenses
  7.  *
  8.  */
  9.  
  10. if(jQuery) (function($) {
  11.    
  12.     // Default settings
  13.     $.formSubmit = {
  14.         defaults: {
  15.             before: null,
  16.             success: null,
  17.             error: null,
  18.             hideInvalid: null,
  19.             showInvalid: null,
  20.             feedbackSuccessClass: '',
  21.             feedbackErrorClass: ''
  22.         }
  23.     };
  24.    
  25.     $.extend($.fn, {
  26.        
  27.         formSubmit: function(method, data) {
  28.            
  29.             switch(method) {
  30.                
  31.                 // Aborts a pending request
  32.                 case 'abort':
  33.                     $(this).each( function() {
  34.                         var form = $(this),
  35.                             xhr = form.data('formSubmit-xhr');
  36.                         if( xhr ) xhr.abort();
  37.                     });
  38.                     return $(this);
  39.                
  40.                 // Getter/setter for the form's busy state
  41.                 case 'busy':
  42.                     if( data === undefined ) return $(this).hasClass('formSubmit-busy');
  43.                     $(this).each( function() {
  44.                         var form = $(this);
  45.                         form.toggleClass('formSubmit-busy', data === true);
  46.                     });
  47.                     return $(this);
  48.                
  49.                 // Releases the form back to its original form and behavior
  50.                 case 'destroy':
  51.                     $(this).each( function() {
  52.                         var form = $(this);
  53.                         form
  54.                             .formSubmit('abort')
  55.                             .formSubmit('reset')
  56.                             .removeData('formSubmit-data')
  57.                             .off('.formSubmit');
  58.                     });
  59.                     return $(this);
  60.                
  61.                 // Sets all the form control's disabled state
  62.                 case 'disabled':
  63.                     $(this).each( function() {
  64.                         var form = $(this);
  65.                         form.find(':input').prop('disabled', data);
  66.                     });
  67.                     return $(this);
  68.                
  69.                 // Resets the form, clears invalids, and hides feedback
  70.                 case 'reset':
  71.                     $(this).each( function() {
  72.                         var form = $(this);
  73.                         hideInvalid(form);
  74.                         hideFeedback(form);
  75.                         form.get(0).reset();
  76.                     });
  77.                     return $(this);
  78.                
  79.                 // Initializes the form
  80.                 case 'create':
  81.                 default:
  82.                     if( method !== 'create' ) data = method;
  83.                    
  84.                     data = $.extend(true, {}, $.formSubmit.defaults, data);
  85.                    
  86.                     $(this).each( function() {
  87.                        
  88.                         var form = $(this),
  89.                             xhr = null;
  90.                        
  91.                         hideFeedback(form);
  92.                        
  93.                         form
  94.                             .data('formSubmit-data', data)
  95.                             .on('submit.formSubmit', function(event) {
  96.                                
  97.                                 event.preventDefault();
  98.                                
  99.                                 // Don't submit if already busy
  100.                                 if( form.formSubmit('busy') ) return;
  101.                                
  102.                                 // Clear invalids and feedback
  103.                                 hideInvalid(form);
  104.                                 hideFeedback(form);
  105.                                
  106.                                 // Submit it
  107.                                 xhr = $.ajax({
  108.                                     url: form.attr('action'),
  109.                                     type: form.attr('method'),
  110.                                     data: form.serialize(),
  111.                                     dataType: 'html',
  112.                                     beforeSend: function(jqXHR) {
  113.                                         if( data.before ) {
  114.                                             // You can cancel the submission by returning false in this callback
  115.                                             if( data.before.call(form, serializeForm(form)) === false ) return false;
  116.                                         }
  117.                                         form.formSubmit('busy', true);
  118.                                     }
  119.                                 })
  120.                                 .error(function(jqXHR, textStatus, errorThrown) {
  121.                                     // Handle AJAX errors
  122.                                     if( data.ajaxError ) data.ajaxError.call(form, textStatus, errorThrown);
  123.                                 })
  124.                                 .always(function(response) {
  125.                                     // Executes after the request has completed (even if it fails)
  126.                                     var i;
  127.                                    
  128.                                     // Update form
  129.                                     form
  130.                                         .removeData('formSubmit-xhr')
  131.                                         .formSubmit('busy', false);
  132.                                    
  133.                                     // Show form field invalid
  134.                                     showInvalid(form, response.invalid);
  135.                                    
  136.                                     // Show feedback
  137.                                     showFeedback(form, response.status, response.feedback);
  138.                                    
  139.                                     // Callbacks
  140.                                     if( response.status === 'success' && data.success ) data.success.call(form, response.data);
  141.                                     if( response.status === 'error' && data.error ) data.error.call(form, response.data);
  142.                                 });
  143.                                
  144.                                 // Remember request
  145.                                 form.data('formSubmit-xhr', xhr);
  146.                            
  147.                         });
  148.                        
  149.                     });
  150.                    
  151.                     return $(this);
  152.                
  153.             }
  154.            
  155.             // Hides all form field errors and triggers the hideInvalid callback
  156.             function hideInvalid(form) {
  157.                 var data = form.data('formSubmit-data');
  158.                 form.find('.formSubmit-invalid').each( function() {
  159.                     $(this).removeClass('formSubmit-invalid');
  160.                     if( data.hideInvalid ) data.hideInvalid.call(this);
  161.                 });
  162.             }
  163.            
  164.             // Hides the feedback
  165.             function hideFeedback(form) {
  166.                 var data = form.data('formSubmit-data');
  167.                 form.find('.formSubmit-feedback')
  168.                     .hide()
  169.                     .removeClass('formSubmit-error')
  170.                     .removeClass('formSubmit-success')
  171.                     .removeClass(data ? data.feedbackErrorClass : '')
  172.                     .removeClass(data ? data.feedbackSuccessClass : '')
  173.                     .html('');
  174.             }
  175.            
  176.             // Serializes form data into an object
  177.             function serializeForm(form) {
  178.                 var o = {};
  179.                 var a = form.serializeArray();
  180.                 $.each(a, function() {
  181.                     if( o[this.name] !== undefined ) {
  182.                         if( !o[this.name].push ) {
  183.                             o[this.name] = [o[this.name]];
  184.                         }
  185.                         o[this.name].push(this.value || '');
  186.                     } else {
  187.                         o[this.name] = this.value || '';
  188.                     }
  189.                 });
  190.                 return o;
  191.             }
  192.            
  193.             // Shows form field errors and triggers the showError callback
  194.             function showInvalid(form, invalid) {
  195.                 var data = form.data('formSubmit-data');
  196.                 if( invalid ) {
  197.                     for( i in invalid ) {
  198.                         form.find('[name=' + invalid[i] + ']').each( function() {
  199.                             $(this).addClass('formSubmit-invalid');
  200.                             if( data.showInvalid ) data.showInvalid.call(this);
  201.                         });
  202.                     }
  203.                 }
  204.             }
  205.            
  206.             // Shows feedback
  207.             function showFeedback(form, status, feedback) {
  208.                 var data = form.data('formSubmit-data');
  209.                 if( feedback ) {
  210.                     if( status === 'success' ) {
  211.                         form.find('.formSubmit-feedback')
  212.                             .addClass('formSubmit-success')
  213.                             .addClass(data.feedbackSuccessClass)
  214.                             .html(feedback).show();
  215.                     }
  216.                     if( status === 'error' ) {
  217.                         form.find('.formSubmit-feedback')
  218.                             .addClass('formSubmit-error')
  219.                             .addClass(data.feedbackErrorClass)
  220.                             .html(feedback).show();
  221.                     }
  222.                 }
  223.             }
  224.            
  225.         }
  226.        
  227.     });
  228.    
  229. })(jQuery);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement