How to get default error of ajax call - javascript

Ok, what I am trying to do is alerting ajax errors according to its error codes and I have lots of ajax calls on website so I am using global ajax error handler function.
But what I want is if some ajax call already have default errors then show there not global.
$(document).ready(function(){
$(document).ajaxError(e,xhr,opt){
if(xhr.error){
//Don't do anything
} else {
alert('You have an error');
}
}
}
First Function :
$.ajax({
type:"post",
url:"page.php",
data:"name=mohit&lastname=bumb",
error:function(){
alert('error');
}
});
Second Function :
$.ajax({
type:"post",
url:"page.php",
data:"name=mohit&lastname=bumb",
});
So in 2nd case it should show You have an error and in first case just error

Yes you can, but you have to override jQuery default $.ajax methods. Check the following code that I used in one of my projects. Make sure you load the script just after jQuery.
My scenario was -
The web site had a lot of ajax partial views which had to check whether user is logged in or not. So I had to override jquery calls to check for it.
I also had to show a loader when any ajax call was made.
One more thing, some js are loaded by ajax, so I added a check whether the url is a .js file or normal url.
I have taken out the sensitive codes that were confidential for my project. The rest is here. This might help you.
$(document).ready(function () {
var oldjQuery = [];
oldjQuery["ajax"] = $.ajax;
oldjQuery["load"] = $.load;
var newOptions = [];
//override ajax
jQuery.ajax = function (options) {
newOptions["ajax"] = $.extend({}, options);
//override the success callback
newOptions["ajax"].success = function (data, textStatus, jqXhr) {
try {
if (options.url.indexOf('.js') <= -1) {
//this is a normal success call, do nothing
}
}
catch (err) {
//... my other codes, incase any error occurred
}
if (typeof options.success != 'undefined') {
//the ajax call has a success method specified, so call it
options.success(data, textStatus, jqXhr);
}
};
//override the error callback
newOptions["ajax"].error = function (jqXhr, textStatus, errorThrown) {
try {
if (options.url.indexOf('.js') <= -1) {
//this is a normal success call, do nothing
}
}catch (y) {
//... my other codes, incase any error occurred
}
//the ajax call has an error method specified, so call it
if (typeof options.error != 'undefined') {
options.error(jqXhr, textStatus, errorThrown);
}
};
return oldjQuery["ajax"](newOptions["ajax"]);
};
//override load function
jQuery.load = function (url, data, completeCallback, ignore) {
newOptions["load"].completeCallback = function (d, textStatus, jqXhr) {
try {
if (url.indexOf('.js') <= -1) {
//codes
}
} catch (err) {
try {
//codes
}catch (err2) {
}
}
if (typeof completeCallback != 'undefined') {
//call the default completed callback
completeCallback(d, textStatus, jqXhr);
}
};
return oldjQuery["load"](url, data, newOptions["load"].completeCallback);
};
});

Related

How to use jquery when on post with success callback

I have an app that needs three different post requests to sync data, I only want one thing to happen when all three are completed but the jquery when is not working. All posts use the success function to process data that the server sent back. Here is my code:
var picUploads = $.post("http://www.epcmapp.co.za/php2/uploadPic.php", {Images: jsonPics}, function (res) {
alert("Ajax Images return");
if(res != "" && res != "53554343455353")
alert(res);
});
var pdfUploads = $.post("http://www.epcmapp.co.za/php2/uploadPDF.php", {PDFs: jsonPDF}, function (res) {
alert("Ajax PDF return");
if(res != "" && res != "53554343455353")
alert(res);
});
var sync = $.post("http://www.epcmapp.co.za/php2/sync.php", {data: json}, function (res) {
alert("Ajax return");
var result = JSON.parse(res);
dropSyncTables();
checkDB();
for (var i in result) {
populateDB(result[i].toString());
}
readDB();
loadProjects();
loadAdditional();
loadProcessRows();
loadAttachments();
});
$.when(picUploads, pdfUploads, sync).then(function() {
$("#loadIcn").attr("src", "images/check3.png");
});
The alerts in the posts do not pop up and the code inside the jquery then never runs. How am I supposed to do this then?
If you need a failure function, you can't use the $.get or $.post functions; you will need to call the $.ajax function directly. You pass an options object that can have "success" and "error" callbacks.
Instead of this:
$.post("/post/url.php", parameters, successFunction);
you would use this:
$.ajax({
url: "/post/url.php",
type: "POST",
data: parameters,
success: successFunction,
error: errorFunction
});
There are lots of other options available too. The documentation lists all the options available.
ref This answer
First check your console.log. You would probably find the issue there. But even if you find it you would always want some kind of errorhandling and this is possible with the deffered objects:
$.when(picUploads, pdfUploads, sync)
.then(function() {
$("#loadIcn").attr("src", "images/check3.png");
})
.fail(function(ts) {
alert('something failed');
console.log(ts.responseText); //Check in console what went wrong here
})
It is also possible to use done() and fail() with $.post (as of jQuery 1.5)
var picUploads = $.post("http://www.epcmapp.co.za/php2/uploadPic.php", {Images: jsonPics}, function (res) {
alert("Ajax Images return");
if(res != "" && res != "53554343455353")
alert(res);
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
});

how to find which method is causing the error during parallel ajax call

I am using $.when to make parallel ajax call to webapi controller and it works perfectly fine. The structure is given below,
$.when(GetDataFromMethodA(),GetDataFromMethodB(),GetDataFromMethodC())
.done(function (responseFromMethodA,responseFromMethodB, responseFromMethodC) {
if (responseFromMethodA != null) {
//do some action
}
if (responseFromMethodB != null) {
//do some action
}
if (responseFromMethodC != null) {
//do some action
}
}).fail(function (xhr, textStatus, errorThrown) {
//which method raised the exception?
});
Methods:
function GetDataFromMethodA() {
var Request = {};
Request.Code = name.find(':selected').val();
return $.ajax({
url: 'api/Data/GetCurrentView',
type: 'POST',
dataType: 'json',
data: Request
});
}
similarly, I have method B and C.
QUESTION:
There are situations where any one of the method fails and based on the failing method, I need to display appropriate message to the user. When anyone of the method fails, the exception is caught in the 'fail' section. But, how to find which method raised the exception?
If you use always instead of done, you can inspect whether the request succeeded with isResolved() or isRejected(), for instance:
$.when(GetDataFromMethodA(),GetDataFromMethodB(),GetDataFromMethodC())
.always(function (responseFromMethodA,responseFromMethodB, responseFromMethodC) {
if(responseFromMethodA.isRejected()) {
console.log('A did not work!');
}
if(responseFromMethodB.isRejected()) {
console.log('B did not work!');
}
// ...etc.
});

Parse XML catch block not catching exception in JS

I have a function that takes an XML file (obtained via AJAX) as input, parses it as XML and then execute some functions on it. A stripped down version can be found below.
AJAX
$.ajax({
type: "GET",
url: "./default.xml",
dataType: "xml",
success: function(data) {
parseMech(data);
}
});
parseMech function
function parseMech(xml) {
try {
var xmlObject = $(xml);
// See the output function below
$(".tree.base").html(treeBuilder(xmlObject.find("node").first()));
console.log("succes?");
} catch(e) {
$("#error-msg > .the-msg").text(" Invalid XML structure").parent().fadeIn(250);
console.log("Failed");
}
}
treeBuilder function
function treeBuilder(nodes) {
var newList = $("<ol>");
nodes.each(function (x, e) {
var newItem = $('<li> </li>');
for (var i = 0, l = e.attributes.length, a = null; i < l; i++) {
// Don't forget to add properties as data-attributes
a = e.attributes[i];
newItem.attr("data-" + a.nodeName, a.value);
if (a.nodeName == "cat" || a.nodeName == "word") {
newItem.html('' + a.value + '');
}
}
if ($(this).children('node').length) {
newItem.append(output($(this).children('node')));
}
newList.append(newItem);
});
return newList;
}
This works as it should when default.xml is a valid xml file. However, when it's not (for instance when I leave out a closing tag) the catch blok is not executed. In other words: when executing all functions with an invalid XML as source, neither console logs are executed, even though you would expect at least one (in try or in catch) to be logged.
Am I missing something here?
You need a fail handler in your ajax call.
According to the docs, a jquery ajax call with a dataType of xml returns a xml doc, so the data stream is being parsed in the course of the ajax call.
Alter the ajax call as follows (behaviour verified):
//...
error: function() {
console.log("ajax failed!");
},
//...
Note
Consider to change the way you specify your handlers,as error and success attributes are deprecated:
top.$.ajax({
type: "GET",
url: url,
crossDomain: true,
dataType: "xml",
})
.fail ( function() {
console.log("ajax failed!");
})
.done ( function(data) {
console.log("ajax ok!");
parseMech(data);
});

refrer function name in ajax, reverse callback on fail

I have no idea how I can achieve this.
I am using jQuery 1.9 for ajax call back.
I have a function, let's say:
function a (param){
//calling a function this will perform ajax
data = performAjax(param, url, etc);
// render response
renderResponse(data);
}
We are executing our ajax in perform ajax function.
Issue is when ajax fails then it perform ajaxError function.
I put a message in div that please refresh this again.
But how can I get function a and all the parameter of that in ajaxError function? So that I can put a link to refresh again.
Not sure if I understand correctly, but here it goes:
function performAjax() {
return $.ajax({
....
});
}
var lastFailedFunction;
function a (param){
var args = arguments;
//calling a function this will perform ajax
performAjax().then(function(data) { // on success
// render reponse
renderResponse(data);
}, function() { // on failure
lastFailedFunction = function() {
a.apply(a, args);
};
// now you can call lastFailedFunction() to try again
});
}
When the ajax-call fails, it will store the failed function call to lastFailedFunction. So somewhere else you might show this message:
<div>Function A failed, click here to try again</div>
Using error callback of ajax, you can get the error message
function a(param) {
var performAjax = $.ajax({
type: "",
url: "",
data: "",
success: function(msg){
//success msg
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
//can access param of fun a and the error message
//append it to the body
$('body').append('<div>'+param+' error: '+errorThrown+'</div>');
}
});
}

Issues with handling http errors with jQuery AJAX webservice calls

I'm developing an jQuery application in where I've a requirement to capture HTTP errors as and when it occurs. Below is my snippet.
// Function to validate URL
function validateURL(url)
{
var pattern = new RegExp();
pattern.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$");
if (!pattern.test(url))
{
return false;
}
return true;
}
// Generic error handler for handling the webservice requests.
function initWebService(wstype, wsurl,jsonData)
{
// If the method parameter is not either "GET" or "POST" display an error message to the developer.
var msgValidateArgument;
var wsCallStatus;
var callbackData;
if ((arguments[0] != 'GET') && (arguments[0] != 'POST'))
{
//alert("Invalid");
//alert("You must provide a valid http method in your webservice call.");
msgValidateArgument = "You must provide a valid http method in your webservice call.";
return msgValidateArgument;
}
// Making sure whether the developer is passing the required number of parameters.
if(arguments.length < 3)
{
//alert("Some required arguments seems to be missing. Please check your webservice invocation.");
msgValidateArgument = "Some required arguments seems to be missing. Please check your webservice invocation.";
return msgValidateArgument;
}
if (!validateURL(arguments[1]))
{
msgValidateArgument = "You must provide a valid URL in your webservice call.";
return msgValidateArgument;
}
if(arguments[2] != ''){
var response=jQuery.parseJSON(arguments[2]);
if(typeof response =='object'){
//It is JSON
alert(response.toSource());
}
else{
msgValidateArgument = "The JSON data being passed is not in valid JSON format.";
return msgValidateArgument;
}
}
// Making the AJAX call with the parameters being passed. The error handler handles some of the possble http error codes as of now.
$.ajax({
type: arguments[0],
url: arguments[1],
data: arguments[2],
dataType: 'json',
async:false,
statusCode:{
404: function(){
alert('Page not found');
},
500: function(){
alert('Page not found');
},
504: function(){
alert('Unknown host');
}
},
success: function(data){
//alert('Data being returned from server: ' +data.toSource());
//alert('Data being returned from server: ' +data.toSource());
//alert(data);
callbackData = data;
}
});
return callbackData;
}
But, when I programatically change the webservice url to hold a wrong value, and upon calling the html page, I'm able to see an error message in the firebug console, but my snippet doesn't seem to be catching the error at all.
For e.g, While calling the GEONames API, I'm encountering an stating "407 Authorization required" in firebug's console.but even if I handle that status code in my error block, it is not firing.. What could be the reason?.
Don't we have any comprehensive solution for handling these HTTP errors effectively?.
I think there are a few problems with your code ... firstly how is handleError called ? because you call a method called handleError but pass nothing ... im assuming your using .ajax()
You should do it like this :
$.ajax({
statusCode: {
404: function() {
alert('page not found');
},
500: function() {
alert('server error');
}
},
success : {
alert('it working');
},
complete : {
alert('im complete');
});

Categories