Last active
January 16, 2017 16:43
-
-
Save matt-allan/4c7466d5b06842095b18a97636ab425c to your computer and use it in GitHub Desktop.
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
$.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