Skip to content

Instantly share code, notes, and snippets.

@objectivehtml
Created September 3, 2012 14:12
Show Gist options
  • Save objectivehtml/3609600 to your computer and use it in GitHub Desktop.
Save objectivehtml/3609600 to your computer and use it in GitHub Desktop.
Authenticate Ajax Submit Example
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
function submit(form, callback) {
var action = form.attr('action');
var post = {};
form.find('input, select, textarea').each(function() {
var $t = $(this);
post[$t.attr('name')] = $t.val();
});
$.post(action, post, function(data) {
if(typeof callback == "function") {
callback(data);
}
});
}
$('form').submit(function(e) {
var form = $(this);
submit(form, function(data) {
if(!data.success) {
var html = '<div class="errors"><h3>Errors</h3><ul>';
$.each(data.errors, function(i, error) {
html += '<li>'+error+'</li>';
});
html += '</ul></div>';
form.find('.errors').remove();
form.prepend(html);
}
else {
window.location = '/';
}
});
e.preventDefault();
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment