Execute a callback when any ajax request is done on my page - javascript

I have a js file (using jQuery) that am making ajax request. The thing is that i want to redirect to 'login' whenever the error.status == 401 (Unauthorized), but i dont want to do this everywhere there is an ajax call.
error: function(e){
if(e.status == 401){
notice(e.responseText+' Please Login.', 'error');
}
}

Define a new function that does what you want and call it inside the error callback:
var errorFunction = function(responsetext) {
notice(responsetext +' Please Login.', 'error');
}
then:
error: function(e){
if(e.status == 401){
errorFunction(e.responseText);
}
}

You can use global ajaxError() and define conditions within it based on settings like url or special properties you can assign to any xhr object within specific requests in beforeSend callback
Example modified from ajaxerror() docs
$( document ).ajaxError(function( event, jqxhr, settings, thrownError ) {
if ( settings.url == "ajax/missing.html" ) {
$( "div.log" ).text( "Triggered ajaxError handler." );
// do a redirect
window.location = '/path/to/login';
}
});

Related

How to get HTTP-StatusCode in ajaxError?

I try to get the HTTP error code in the generic $(document).ajaxError() method. How can I read it out? I found this jQuery: How to get the HTTP status code from within the $.ajax.error method? but I don't manage to adapt it to my function.
JQuery version is 2.1.3.
$(document).ajaxError(function (jqXHR, textStatus, errorThrown) {
if (jqXHR.statusCode != "500") {
$("#global-error-wrapper").show();
$(".global-error-message-inner-text").text(trans("noconnectionerror"));
}
});
You are using ajaxError which seems to be a bit different than the ajax event error handler defined in the settings in the link you posted. For ajaxError(), it looks like the first parameter in the callback is the event and the second is the jqXHR object you want. Also it should be jqXHR.status and not statusCode Try the below
$(document).ajaxError(function (event, jqXHR, settings, thrownError) {
if (jqXHR.status != 500) {
$("#global-error-wrapper").show();
$(".global-error-message-inner-text").text(trans("noconnectionerror"));
}
});
The statusCode object on the jqXHR object in your ajaxError method refers to an object mapping that you can create when you build your ajax call. If you have an idea of what status codes to expect, you could build out this mapping and send it along with your ajax calls which could help you identify what status code was returned:
var statusCodeMapping = {
404: function() {
$notFound = true;
}
}
$.ajax({
statusCode: statusCodeMapping
});
You could then examine the $notFound object to see if that was the status code returned from your Ajax call:
$(document).ajaxError(function (jqXHR, textStatus, errorThrown) {
if ($notFound) {
$("#global-error-wrapper").show();
$(".global-error-message-inner-text").text(trans("noconnectionerror"));
}
});
The $notFound object should be global to your script

jquery wait for ajax load to complete after click event

I'm working on a magento site which uses ajax layered navigation. When the user clicks on a color link in the layered nav it loads a list of the relevent products. I want to fire a click event after the ajax has completed.
I thought I could use the jQuery when() function for this but I can't get it working.
jQuery( "a#red-hoi-swatch" ).click(function() {
jQuery.when( jQuery.ajax() ).then(function() {
jQuery("a[name*='chili-ireye']").click();
});
});
Basically, I want to run jQuery("a[name*='chili-ireye']").click(); after the ajax has finished when a user clicks the a#red-hoi-swatch.
UPDATE
I found the ajax responsible for this, it's from the Magento Blacknwhite theme we bought
/*DONOT EDIT THIS CODE*/
function sliderAjax(url) {
if (!active) {
active = true;
jQuery(function($) {
oldUrl = url;
$('#resultLoading .bg').height('100%');
$('#resultLoading').fadeIn(300);
try {
$('body').css('cursor', 'wait');
$.ajax({
url: url,
dataType: 'json',
type: 'post',
data: data,
success: function(data) {
callback();
if (data.viewpanel) {
if ($('.block-layered-nav')) {
$('.block-layered-nav').after('<div class="ajax-replace" />').remove();
$('.ajax-replace').after(data.viewpanel).remove();
}
}
if (data.productlist) {
$('.category-products').after('<div class="ajax-category-replace" />').remove();
$('.ajax-category-replace').after(data.productlist).remove();
}
var hist = url.split('?');
if(window.history && window.history.pushState){
window.history.pushState('GET', data.title, url);
}
$('body').find('.toolbar select').removeAttr('onchange');
$('#resultLoading .bg').height('100%');
$('#resultLoading').fadeOut(300);
$('body').css('cursor', 'default');
ajaxtoolbar.onReady();
jQuery('.block-layered-nav a').off('click.vs');
try{
ConfigurableSwatchesList.init();
}catch(err){}
}
})
} catch (e) {}
});
active = false
}
return false
}
function callback(){
}
I was able to achieve this with the ajaxComplete() function:
jQuery( "a#red-hoi-swatch" ).click(function() {
jQuery(document).ajaxComplete(function(){
jQuery("a[name*='chili-ireye']").click();
});
});
Not done jQuery for a while but do you really need the .when()?
Can you not just do
jQuery( "a#red-hoi-swatch" ).click(function() {
var url = 'http://my/api/url';
jQuery.ajax(url).then(function() {
jQuery("a[name*='chili-ireye']").click();
});
});
You can make any of the following 3
calling your click event on the success of your ajax call
you can make the asynch property of your ajax call to false;
callback the click event on success of your ajax call.
You can use handlers just after ajax queries or you can define a success callback for the ajax query.
From the jQuery API:
// Assign handlers immediately after making the request,
// and remember the jqXHR object for this request
var jqxhr = $.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function() {
alert( "second complete" );
});

how can i place two callback functions in a .load() function in jquery?

I'm having issues figuring out how to handle error on my page using .load() function, i already used the call back function for transitioning and i don't know how or to place the error code and make it work correctly....
i av this code.....
$('.menuLink:eq(0)').click(function(event) {
event.preventDefault();
setTimeout($('#navigation ul li').removeClass('expand', 'normal'), 1000);
$('section').hide().load('index.html section', function() {
$(this).fadeIn('slow');
});
});
I'll like to load any error that may occur in the section tag...
If you are using load() you can do the error checking in the same callback function. For example, as given in the JQuery documentation:
Display a notice if the Ajax request encounters an error.
<script>
$( "#success" ).load( "/not-here.php", function( response, status, xhr ) {
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
$( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
}
});
</script>
In that callback function, first check for errors. Then, if there are no errors, do the fadeIn.
$('.menuLink:eq(0)').click(function(event) {
event.preventDefault();
setTimeout($('#navigation ul li').removeClass('expand', 'normal'), 1000);
$('section').hide().load('index.html section', function() {
// Check for errors here
$(this).fadeIn('slow');
});
});

Capture a response from jquery submitForm

I have the following code that I use with Yii framework to delete one register.
This code is automatic generated and I'd like to capture if it was submited when the dialog open. If the ajax is complete I'll save in my user log.
jQuery(function($) {
jQuery('body').on('click','#yt0', function(){
if (confirm('Want to delete it?')) {
jQuery.yii.submitForm(this,'/yiiProject/index.php?r=project/delete&id=168',{});
return false;
}
else
return false;
});
jQuery('body').tooltip({'selector':'a[rel=tooltip]'});
jQuery('body').popover({'selector':'a[rel=popover]'});
});
Most you can do as far as I can see is override the confirm method and handle the case when user click OK:
var originalConfirm = window.confirm;
window.confirm = function(msg) {
if (originalConfirm(msg)) {
//log...
return true;
}
return false;
};
You can also override Yii auto generated code completely by sumbitting the AJAX yourself then always returning false:
if (originalConfirm(msg)) {
$.post("/yiiProject/index.php?r=project/delete&id=168", function() {
//success, write to log...
});
return false;
}
Try to use the global ajax events:
http://api.jquery.com/ajaxSuccess/
$( document ).ajaxSuccess(function( event, xhr, settings ) {
if ( settings.url == "ajax/test.html" ) {
$( ".log" ).text( "Triggered ajaxSuccess handler. The ajax response was: " +
xhr.responseText );
}
});

help with jquery ajax success event

I'm having an issue with my update button and jquery ajax. Right now when I click on my update button, it saves whatever updated data to the database. My goal is I want to slide up a message if the update is successful. I was looking at ajax post and using the success event seems like it would work but I dont know how to incorporte it. How would I do this? Would it be something like this?
$(document).ready(function(){
$('#divSuccess').hide();
$('#btnUpdate').click( function() {
alert('button click');
$.ajax({
url: "test.aspx",
context: document.body,
success: function(){
$('#divSuccess').show("slide", { direction: "down" }, 3000);
$('#divSuccess').hide("slide", { direction: "down"}, 5000);
}
});
});
});
check out this question for an example on how to handle the success event. Hope this helps!
$("#targetDiv").load("page.php",$("#form").serializeArray(),function (response)
{
if (response == '0' && response != '')
alert('Request not sent to server !\n');
else if(response == '-1')
alert('Please write some more !\n');
else
{
alert("success! ");
}
}
);
i've echo ed 0 and -1 for failure and other for success
In the jquery post function, you can execute some callback function.
function (data, textStatus) {
// data could be xmlDoc, jsonObj, html, text, etc...
this; // the options for this ajax request
// textStatus can be one of:
// "timeout"
// "error"
// "notmodified"
// "success"
// "parsererror"
// NOTE: Apparently, only "success" is returned when you make
// an Ajax call in this way. Other errors silently fail.
// See above note about using $.ajax.
}
http://docs.jquery.com/Post
With at least jQuery 1.5, you've got deferred objects and new syntax for AJAX events (including success).
var $ajaxcall = $.ajax({
url : 'myurl.svc/somemethod',
data : '{ somedata : "sometext" }'
});
$ajaxcall.success(function() {
// do something on successful AJAX completion
});
Of course you can chain that as well, and call something along the lines of $.ajax().success() or something.
Just wrote a blog post on it myself, if you're interested in reading more.

Categories

Resources