Error handling for jQuery ajax load() - javascript

I am loading ajax load
function ajaxPageFilter(filterDiv, filterLink, filterName, loaderDivId, loaderId) {
jQuery("#" + filterDiv).load(filterLink, {'filterName': filterName}, function(data) {
jQuery("img.lazy").lazyload({effect : "fadeIn"});
jQuery('#'+loaderDivId).remove();
jQuery('#'+loaderId).remove();
});
}
Is there a way to do error handling for ajax load, in case if it fails.
thanks

You can capture the status argument in your callback, and have a condition to check if there is an error.
jQuery("#" + filterDiv).load(filterLink, {'filterName': filterName}, function(data, status) {
if(status == "error"){
// do something
} else {
jQuery("img.lazy").lazyload({effect : "fadeIn"});
jQuery('#'+loaderDivId).remove();
jQuery('#'+loaderId).remove();
}
});

Related

Identifying AJAX request

I am triggering multiple AJAX requests in a loop. They run in parallel and it is not clear which one will respond first.
If the response is successful, I can identify the request by analyzing the response.
for (kk = 0; kk < $('#style').val().length; kk++){
$.ajax({
type: "POST",
url: "/single",
data: {style: [$('#style').val()[kk]]},
success: function (results) {
if (results.status == 'success'){
$('#results').find('div').each(function(){
if ($(this).attr('id') == results.style){
$(this).empty().append(results.payload)
}
});
}
else{
$('#results').find('div').each(function(){
if ($(this).attr('id') == results.style){
$(this).empty().append('<b>' + results.style + ':</b> ' + results.payload)
}
});
}
},
error: function (error) {
console.log(error);
}
});
}
However, once in a while, the request fails and an error is triggered.
For a proper error handling, I would like to know to which of the (previously triggered) requests the error belongs.
Is there a clean method how a specific AJAX request can be identified?
I would recommend to pass in a identifier via context to the AJAX call which you can use inside the success or error methods:
for (kk = 0; kk < $('#style').val().length; kk++){
$.ajax({
type: "POST",
url: "/single",
data: {style: [$('#style').val()[kk]]},
// data inside "context" will be available as part of "this" in the success/error case.
context: {
"kk": kk
},
success: function (results) {
if (results.status == 'success'){
console.log("Element " + this.kk + " finished successfully.");
$('#results').find('div').each(function(){
if ($(this).attr('id') == results.style){
$(this).empty().append(results.payload)
}
});
}
else{
$('#results').find('div').each(function(){
if ($(this).attr('id') == results.style){
$(this).empty().append('<b>' + results.style + ':</b> ' + results.payload)
}
});
}
},
error: function (error) {
console.log("Element " + this.kk + "failed.");
console.log(error);
}
});
}
More information regarding context can be found in the jQuery documentation.
Regarding your comment about checking how many calls failed / succeeded: here is a JsFiddle demonstrating how to keep track of the call statistics.

Error on recursive method call

I need to fetch data from and external API. Since I have to make the call again and again to check the status until the status is TRUE, I have placed it in a recursive loop. I need to know what's wrong with my logic, because I'm unable to get the desired output. Does the response.status update itself or do i need to make another ajax like how I have done in the code
fetchFunct();
function fetchFunct(){
console.log("entered function");
$.ajax
({
type: "GET",
url: "/content/mosaic/multi/preview/status/"+testId ,
async: false,
dataType : "json",
success : function(response)
{
console.log(response);
if(response.status === false)
{
console.log("Processing details"); //show still in progress
$("#load").show();
$("#heading").hide();
$("#b1").hide();
$("#b2").hide();
$("#b3").hide();
$("#b4").hide();
$("#b5").hide();
}else
{
$("#load").hide();
console.log("Loading 1");
$("#b1").click(function(){
$("#ad22img").attr("src","http://" + response.images.android22);})
console.log("Loading 2");
$("#b2").click(function(){$("#ad4img").attr("src","http://" + response.images.android4);})
console.log("Loading 3");
$("#b3").click(function(){ $("#apm6img").attr("src","http://" + response.images.appmail6);})
console.log("Loading 4");
$("#b4").click(function(){ $("#blbimg").attr("src","http://" + response.images.blackberryhtml);})
console.log("Loading 5");
$("#b5").click(function(){$("#iphnimg").attr("src","http://" + response.images.iphone5s);})
is_loaded = true;
}
}
}).fail(function(data) { console.log("FAIL"); }).done(function(data) { console.log("coming out of ajax");
});
if(!is_loaded)
{
console.log("entered if");
delay=delay*2;
if(delay>60)
{delay=1;}
setTimeout(fetchFunct,delay*1000);
}
//console.log("if not entered");
}
You should call your function again inside the callback function.
if(response.status === false)
{
console.log("Processing details"); //show still in progress
$("#load").show();
$("#heading").hide();
$("#b1").hide();
$("#b2").hide();
$("#b3").hide();
$("#b4").hide();
$("#b5").hide();
//Try again
setTimeout(function(){
fetchFunct();
},1000);
}else
No need for any of the setTimeout logic beneath your AJAX call.

AJAX request confusion in jQuery

I am unable to understand that why the jquery AJAX is not fetching data from the ajax page.
Can someone please help.
<script type="text/javascript">
$(function() {
$('#lms_id').change(function(){
if ($(this).val() != "") {
// alert("1");
} else {
// alert("0");
}
});
$('#lms_user_role_id').change(function(){
if (($(this).val() == "7" || $(this).val() == "8")) {
$('#t_lms_dealers').show();
} else {
$('#t_lms_dealers').hide();
}
});
});
function loadAjax(message)
{
//alert(message);
//$.get("<?php echo $App['wwwroot'].'er.php' ?>?activity="+message);
$.get("http://www.abc.loc/er.php");
}
</script>
In loadAjax function, alert is alerting fine, but only the AJAX part is not working.
How do you know it is "not working"?
$.get("http://www.abc.loc/lmsapi/LMS_L2/templates/admin/user/tpl.user_dealer.php");
Even if it did, this statement would accomplish nothing. You need to put a handler in there:
$.get(
"http://www.abc.loc/lmsapi/LMS_L2/templates/admin/user/tpl.user_dealer.php",
function (data) {
alert("Retrieved :"+data);
}
);
You should also use some kind of in browser developer tool (eg, firebug) that will allow you to trace the request in real time. Finally, the plain jquery get lacks an error handler; you might want to instead use:
$.ajax ({
url: "http://www.abc.loc/lmsapi/LMS_L2/templates/admin/user/tpl.user_dealer.php",
success: function (data) {
alert(data);
},
error: function (xhr, err, code) {
alert("Error: "+err);
}
});
And read the query documentation:
http://api.jquery.com/category/ajax/
if i am not wrong 2nd possibility is may be you are trying "cross domain ajax call", if yes then you have to set header "Access-Control-Allow-Origin" and "crossDomain: true" for $.ajax call.

Why does IE8 error on $.post() ["Object doesn't support this property or method"]?

I've searched high and low, but can't find this even being mentioned. Using jQuery 1.4.4 (and no other library), this so far only happens on Internet Explorer 8. The error is "Object doesn't support this property or method", and the line it points to is below, at $.post(.
The JS
The HTML is unexceptional, so I'm just going to post JS.
$(window).load(function(){
$("input[type='submit']", ".scope").live("click", function(e){
e.preventDefault();
// some intervening code defining variables used below...
//only var which is at all complex
var inputs = $form.find(":input").serializeArray();
$.post(
action,
inputs,
function(data){
var $json = $.parseJSON(data);
if ( $json.success == true ) {
if ( testVar == 2 ) {
if ( $json.tabkill == true ) {
killTab(tabID);
} else {
loadPane(rID,tabID,"refreshTop");
}
} else {
loadPane(rID,tabID);
}
} else {
//modal dialogue error message, excised
}
}
).ajaxError(function(e, xhr, settings, exception) {
if (settings.url == action) {
alert("Problem calling: "+settings.url+"\n code: "+xhr.status+"\n exception: "+exception);
}
});
return false;
});
//end window load block
});
The problem is with your line ajaxError.
The problem is that $.post returns an XMLHTTPRequest object, not a jQuery selection. ajaxError must be called on a jQuery selection.
There are two safe ways around this:
1) Upgrade to jQuery 1.5. This introduces a new XMLHTTPRequest wrapper object jqXHR. You can use the error handler in the way that you are attempting:
$.post(
action,
inputs,
function(data){
/* ... */
}
).error(function(){
alert ("Problem calling: " + action + "\nCode: " + this.status + "\nException: " + this.statusText);
});
2) Use a call direct to $.ajax and set an error handler:
$.ajax({
url: action,
data: inputs,
success: function(data){
/* ... */
},
error: function(xhr, textStatus, error) {
alert("Problem calling: " + action + "\nCode: " + xhr.status + "\nException: " + textStatus);
}
});
It is because the ajaxError()(docs) method needs to be called against a jQuery object, and the $.post()(docs) method returns an XMLHttpRequest object.
Not sure why you don't get an error in other browsers.
I think this is invalid:
).ajaxError(function(e, xhr, settings, exception) {
if (settings.url == action) {
alert("Problem calling: "+settings.url+"\n code: "+xhr.status+"\n exception: "+exception);
}
});
it should be attached to a jQuery object.
EDIT: what patrick said.

jquery xml exists

I want to use javascript / jquery to determine if an xml file exists.
I don't need to process it; I just need to know whether it's available or not,but I can't seem to find a simple check.
Here is what I've tried:
jQuery.noConflict();
jQuery(document).ready(function(){
var photo = '223';
var exists = false;
jQuery.load('/'+photo+'.xml', function (response, status, req) {
if (status == "success") {
exists = true;
}
});
});
Assuming you are talking about an xml file on the server, you could do a ajax request and then write a custom error handler to check the error response message. You'll need to know what the exact error message code is for a missing file (usually 404). You can use Firebug Console to check what the exact error message and code is.
$.ajax({
type: "GET",
url: "text.xml",
dataType: "xml",
success: function(xml) {
alert("great success");
},
error: function(xhr, status, error) {
if(xhr.status == 404)
{
alert("xml file not found");
} else {
//some other error occured, statusText will give you the error message
alert("error: " + xhr.statusText);
}
} //end error
}); //close $.ajax(
Your question isn't clear to me. If I understand, you want to verify whether a file (the XML) is present or not in the HTTP server.
That's correct? If so, you can just do:
$.get('url-to-file.xml', function(response, status, req) {
if (status == 'success') {
alert('exists');
}
});
EDITED: As pointed by #lzyy on comments, .get() only calls the callback upon success. However, I'd stick to the .load() using $(document) as selector. See:
$(document).load('url-to-file.xml', function(response, status, req) {
if (status == 'success') {
alert('exists');
} else if (status == 'error') {
alert('doesnt exist');
}
});

Categories