Skip to content

Instantly share code, notes, and snippets.

@selahattinunlu
Created January 28, 2016 13:14
Show Gist options
  • Save selahattinunlu/9d6fcac3c73ecea00bfe to your computer and use it in GitHub Desktop.
Save selahattinunlu/9d6fcac3c73ecea00bfe to your computer and use it in GitHub Desktop.
jquery-ajax-global-setup
$(document).ajaxError(function(event, xhr, settings) {
if (! settings.globalRequest) return;
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, label');
wrapper.addClass('has-error');
wrapper.append('<div class="help-block">'+ errors[0] +'</div>');
});
break;
}
});
$(document).ajaxSuccess(function(event, xhr, settings) {
if (! settings.globalRequest) return;
var response = xhr.responseJSON;
if (response.success && response.redirect) {
window.location.href = response.redirect;
}
});
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (! settings.globalRequest) return;
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