Created
January 28, 2016 12:31
-
-
Save selahattinunlu/2b7d1168ac27b667748a to your computer and use it in GitHub Desktop.
Jquery Global Ajax Error Handler (For Form Validation Messages)
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
/********************************** | |
-------------------- | |
Sample Request | |
-------------------- | |
$.ajax({ | |
wrapperElement: $('form#wrapperElementClassOrId'), | |
url: url, | |
type: 'POST', | |
dataType: 'json', | |
data: $(this).serialize(), | |
success: function(response) { | |
} | |
}); | |
*************************************/ | |
$(document).ajaxError(function(event, xhr, settings) { | |
var response = xhr.responseJSON; | |
switch (xhr.status) { | |
case 422: | |
$.each(response.error, function(key, errors) { | |
var input = $('[name="'+ key +'"]'); | |
var wrapper = input.parents('.form-group'); | |
wrapper.addClass('has-error'); | |
wrapper.append('<div class="help-block">'+ errors[0] +'</div>'); | |
}); | |
break; | |
} | |
}); | |
$.ajaxSetup({ | |
beforeSend: function(xhr, settings) { | |
if (! settings.wrapperElement) { | |
console.warn('Before send methodunun çalışması için ajax isteğine wrapperElement tanımlaması yapılmalı.'); | |
return; | |
} | |
settings.wrapperElement.find('.has-error').removeClass('has-error'); | |
settings.wrapperElement.find('.help-block').remove(); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment