Created
          August 8, 2012 19:53 
        
      - 
      
- 
        Save jamesarosen/3298047 to your computer and use it in GitHub Desktop. 
    jQuery function that causes a form to submit via AJAX
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | function buildSubmitHandler(ajaxOptions) { | |
| function submitViaAJAX(event) { | |
| var data = $.extend( {}, ajaxOptions.data, $form.serialize() ), | |
| options = $.extend({}, { | |
| url: $form.attr('action'), | |
| type: $form.attr('method'), | |
| }, ajaxOptions, { data: data }); | |
| $.ajax(options) | |
| .done( $.proxy($form.trigger, $form, 'submitdone') ) | |
| .fail( $.proxy($form.trigger, $form, 'submitfail') ) | |
| .always( $.proxy($form.trigger, $form, 'submitalways') ) | |
| return false; | |
| }; | |
| return submitViaAJAX; | |
| } | |
| jQuery.fn.submitViaAJAX = function(ajaxOptions) { | |
| return this.each(function(i, form) { | |
| $(form).submit( buildSubmitHandler(ajaxOptions) ); | |
| }); | |
| }; | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | <form action="/foo" method="post" id='my_form'> | |
| <label>Name: <input name="name" /></label> | |
| </form> | |
| <script type="text/javascript"> | |
| $('#my_form') | |
| .submitViaAJAX() | |
| .bind('submitdone', function(ajaxResponse) { | |
| alert('Submitted!'); | |
| }); | |
| </script> | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment