Last active
August 29, 2015 14:01
-
-
Save emersonbroga/fd183bae93127f7fc1ac to your computer and use it in GitHub Desktop.
Dynamic call for ajax forms using jQuery
This file contains 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
// Dynamic call for ajax forms using jQuery | |
// <form method='post' data-async="true" data-callback="functionName" > callback function | |
// <form method='post' data-async="true" data-callback="Object.mehodName" > callback object method | |
// will send 3 params to callback function: form, data, result | |
$('body').on('submit', 'form[data-async]', function(e) { | |
e.preventDefault(); | |
var $form = $(this), | |
callback = $form.attr('data-callback');// or $form.data('callback'); on newest jQuery versions | |
$.ajax({ | |
type: $form.attr('method'), | |
url: $form.attr('action'), | |
data: $form.serialize(), | |
success: function(data, status) { | |
// check if has dot (Object.method) else if it's a function. | |
if( callback.indexOf('.') !== -1){ | |
var parts = callback.split('.'); | |
if(parts.length == 2){ | |
var _object = window[parts[0]]; | |
var _method = parts[1]; | |
if( _object.hasOwnProperty(_method)){ | |
_object[_method]( $form[0], data, status ); | |
} | |
} | |
} | |
//if it's callback function | |
else if(typeof(window[callback]) === 'function'){ | |
window[callback]($form[0], data, status); | |
} | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment