Skip to content

Instantly share code, notes, and snippets.

@matt-allan
Last active January 16, 2017 16:43
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matt-allan/4c7466d5b06842095b18a97636ab425c to your computer and use it in GitHub Desktop.
Save matt-allan/4c7466d5b06842095b18a97636ab425c to your computer and use it in GitHub Desktop.
$.ajax({
method: POST,
url: my.app.dev/users/1,
data: { name: "Matt"}
})
.done(function () {
// whatever you normally do here
})
.fail(function (res) {
if (res.status !== 422) {
// some other error. Just render a popup or something.
alert('There was an error saving your work. Maybe try again?');
return;
}
// otherwise you can parse the response text and get the errors.
var errors = JSON.parse(res.responseText);
// First clear out any existing errors.
$('.my-class form').find('.help-block').text('');
for (var name in errors) {
// First find the input element that matches this error
var $input = $('.my-class form')
.find('[name=' + name + ']')
.first();
// Set the has-error class for bootstrap
$input.parents('.form-group').addClass('has-error');
// Render the error message in the .help-block div.
$input.parents('.form-group').find('.help-block').text(errors[name]);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment