Created
February 13, 2014 20:30
-
-
Save jtmitchell/8983230 to your computer and use it in GitHub Desktop.
Javascript to submit forms with class ajax-form, and expect an ajam response to put onto the page
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
| // General jQuery function to autosubmit forms with a class of 'ajax_form' and put the return html into a div | |
| // the .spin() function is from http://fgnass.github.io/spin.js/ | |
| $('.ajax_form').live('submit',function() { // catch the form's submit event | |
| this_form = this; | |
| replace_div = $(this).attr('data-replace-div'); | |
| $(replace_div).spin(); // start the busy spinner | |
| $.ajax({ | |
| data: $(this).serialize(), // get the form data | |
| type: $(this).attr('method'), // GET or POST | |
| url: $(this).attr('action'), | |
| success: function(response, status, xhr) { | |
| $(replace_div).spin(); // turn off the spinner | |
| var content_type = xhr.getResponseHeader("content-type") || ""; | |
| if(content_type.indexOf('html') > -1){ // handle HTML response versus JSON | |
| $(replace_div).html(response); | |
| } | |
| if(content_type.indexOf('json') > -1){ | |
| if(typeof response['replace-div'] !== 'undefined'){ | |
| replace_div = response['replace-div']; | |
| } | |
| if(typeof response['toggle-div'] !== 'undefined'){ | |
| $(response['toggle-div']).toggle(); | |
| } | |
| if(typeof response['html'] !== 'undefined'){ | |
| $(replace_div).html(response['html']); | |
| } | |
| if(typeof response['meerkat'] !== 'undefined'){ | |
| show_message_bar(response.meerkat['status'],response.meerkat['message'],response.meerkat['extra_message'],3,0); | |
| } | |
| } | |
| $(replace_div).find('.tooltip').tipTip(); | |
| $(replace_div).find('.meerkat-reponse').each(function(){ | |
| // look for a message that should be displayed with the meerkat slider | |
| var message = $(this).attr('data-meerkat-response'); | |
| show_message_bar('success',message,'',3,0); | |
| }); | |
| }, | |
| error: function(response, status, error){ | |
| $(replace_div).spin(); // turn off the spinner | |
| show_message_bar('error',response.responseText,'',null,0); | |
| } | |
| }); | |
| return false; | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment