I'm having a trouble with ajax requests and server responses:
$.ajax({
url: servurl,
dataType: "jsonp",
data: {... },
crossDomain: true,
error: function(){},
success: function(){},
complete: function(){alert('complete')}
});
}
The thing is - sometimes I get succes, when I should get it, but sometimes I can get 500 status, and it is normal and expected.
The same ajax call works for correct requests, but fails for others.
I want to display an error message if I get a 500 server error, but for some reason the ajax does not complete. Thus, neither error: nor complete: work.
Maybe the reason for that is 'jsonp' datatype? Other datatypes do not work though.
Can someone help please?
Or maybe give me an advice on how to detect server status any other way.
jsonp requests do not trigger error callbacks by design, therefore there is no way for you to catch the error with javascript. I suggest instead implementing an error handler on your server that detects a jsonp request and returns jsonp that indicates an error has occured rather than a 500 status code.
Note that error: is deprecated as of 1.8 and is not called for JSONP however I wonder if you might have success using the Promise functionality introduced with 1.5 for deferred http://api.jquery.com/category/deferred-object/ as:
jqXHR.fail(function(jqXHR, textStatus, errorThrown) {});
jqXHR.done(function(data, textStatus, jqXHR) {});
jqXHR.always(function(data|jqXHR, textStatus, jqXHR|errorThrown) { });
Example for your code:
$.ajax({
url: servurl,
dataType: "jsonp",
data: {... },
crossDomain: true
}).done(function(data, textStatus, jqXHR){ //replace success
alert(textStatus);
}).always(function(data|jqXHR, textStatus, jqXHR|errorThrown) { // replace complete
alert(textStatus);
}).fail(function(jqXHR, textStatus, errorThrown) { // replace error
alert(errorThrown);
});
Make sure that you are accessing to your server. Maybe you are requesting in your server for an specific contentType (like application/json) and you are not using that property into your ajax call.
As you requested, to show any message if get a error (400, 404, 500...), you can use my custom function for ajax error responses:
function onErrorFunc(jqXHR, status, errorText) {
alert('Status code: ' + jqXHR.status + '\nStatus text: ' + status +
'\nError thrown: ' + errorText);
}
Usage:
$.ajax({
//some options
error: onErrorFunc
});
Please, show us what error thrown your server.
Thank you all for comments. Jquery .ajax really does not give errors on jsonp requests.
The way to get error messages was to implement the jquery-jsonp plugin:
https://github.com/jaubourg/jquery-jsonp
Related
I'm making an ajax jsonp request, but the failure error handling wont work. If the request is 404 or 500 it won't handle the error.
I've been looking around to find an answer to this, but can't find anything. There seems to be a solution with http://code.google.com/p/jquery-jsonp/, but I can't find any examples on how to use it.
function authenticate(user, pass) {
$.ajax ({
type: "POST",
url: "url",
dataType: 'jsonp',
async: false,
//json object to sent to the authentication url
data: {"u": userid, "p": pass},
success: function (data) {
//successful authentication here
console.log(data);
},
error: function(XHR, textStatus, errorThrown) {
alert("error: " + textStatus);
alert("error: " + errorThrown);
}
})
}
If you check jQuery.ajax() documentation, you can find:
error
A function to be called if the request fails (...) Note: This handler is not called for cross-domain script and cross-domain JSONP requests. This is an Ajax Event.
Because of that, you're forced to find workaround. You can specify timeout to trigger an error callback. It means that within specified time frame the request should be successfully completed. Otherwise, assume it has failed:
$.ajax({
...
timeout: 5000, // a lot of time for the request to be successfully completed
...
error: function(x, t, m) {
if(t==="timeout") {
// something went wrong (handle it)
}
}
});
Other issues in your code...
While JSONP (look here and here) can be used to overcome origin policy restriction, you can't POST using JSONP (see CORS instead) because it just doesn't work that way - it creates a element to fetch data, which has to be done via GET request. JSONP solution doesn't use XmlHttpRequest object, so it is not an AJAX request in the standard way of understanding, but the content is still accessed dynamically - no difference for the end user.
$.ajax({
url: url,
type: "GET"
dataType: "jsonp",
...
Second, you provide data incorrectly. You're pushing javascript object (created using object literals) onto the wire instead of its serialized JSON representation. Create JSON string (not manually, use e.g. JSON.stringify converter):
$.ajax({
...
data: JSON.stringify({u: userid, p: pass}),
...
Last issue, you've set async to false, while documentation says:
Cross-domain requests and dataType: "jsonp" requests do not support
synchronous operation.
Two ways to handle error,
There is no error handling for cross domain JSONP requests. Use jsonp plug-in available on Github https://github.com/jaubourg/jquery-jsonp that provides support for error handling.
jQuery ajax Timeout - Timeout after a reasonable amount of time to fire the error callback because it might have failed silently. You may not know what the actual error (or error status) was but at least you get to handle the error
I've been struggling like you for a while trying to handle errors on ajax jsonp DataType requests, however I want to share you my code, hope it helps. A basic thing is to include a timeout on the ajax request, otherwise it'll never enter the error: function
$.ajax({
url: "google.com/api/doesnotexists",
dataType: "jsonp",
timeout: 5000,
success: function (parsed_json) {
console.log(parsed_json);
},
error: function (parsedjson, textStatus, errorThrown) {
console.log("parsedJson: " + JSON.stringify(parsedjson));
$('body').append(
"parsedJson status: " + parsedjson.status + '</br>' +
"errorStatus: " + textStatus + '</br>' +
"errorThrown: " + errorThrown);
}
});
jsfiddle - Handle Errors with jquery ajax call and JSONP dataType - Error 404
I'm building a fragile JS project that uses jquery-jsonp, and came up with a dual-jsonp/ajax approach that handles errors no matter which method ends up being used.
function authenticate(user, pass) {
var ajax = ($.jsonp || $.ajax)({
'url': /* your auth url */,
'data': { /* user, pass, ... */ },
'contentType': "application/javascript",
'dataType': 'jsonp',
'callbackParameter': 'callback' // $.jsonp only; $.ajax uses 'jsonpCallback'
});
ajax.done(function (data) {
// your success events
});
ajax.fail(function (jqXHR, textStatus, errorThrown) {
// $.jsonp calls this func as function (jqXHR, textStatus)
// and $.ajax calls this func with the given signature
console.error('AJAX / JSONP ' + textStatus + ': ' +
(errorThrown || jqXHR.url));
});
}
Since both jquery-jsonp and $.ajax support the jQuery Deferred specification, we can merge the two error handlers together, handling 400 and 500-series errors, as well as lookup timeouts.
Old question but I had the same problem. Here is a solution that worked for me.
If you own the domain you shoot your request at, you can set a variable in the response and check for it on the client side.
Server Side:
SERVER_RESPONSE=true; Callback(parameter1, parameter2);
Client Side:
if(typeof SERVER_RESPONSE === 'undefined'){
console.log('No Response, maybe server is down');
}
else{
console.log('Got a server response');
}
I am making Ajax call with Jsonp DataType. And the JsonpCallback Function gets executed, while processing JsonpCallBack method, it throws error as '
parse error , MyScript.JsonpSuccessCallBack was not called'
While Debugging , i got that the error is hitted from AjaxCovert function(return statement) in jquery Library file.
var MyScript = {};
$.ajax({
url: 'https:' + domain + 'captcha/captcha-generate-token',
type: 'GET',
contentType: "application/json; charset=utf-8;",
async: true,
dataType: "jsonp",
jsonpCallback: 'MyScript.JsonpSuccessCallBack',
error:MyScript.error,
});
MyScript.JsonpSuccessCallBack = function(response){
//stuffs
}
MyScript.error = function(jqXHR, textStatus, errorThrown){
console.log(errorThrown);
}
I am getting a valid API response with MyScript.JsonpSuccessCallBack({"STATUS":"success","CONTENT_TYPE":"application\/json","CK":"wTnoiHvP-eLyCWO0xG-KIrJ3AXnLm7awLH-xETjLPNLd4Kkt"})
The error thrown is as below
Error: MyScript.JsonpSuccessCallBack was not called
at Function.jQuery.extend.error (http://www.someWebsite.com/web/scripts/jquery/jquery.js:248:9)
at jQuery.ajaxPrefilter.s.converters.script json (http://www.someWebsite.com/web/scripts/jquery/jquery.js:9893:12)
at ajaxConvert (http://www.someWebsite.com/web/scripts/jquery/jquery.js:8843:19)
at done (http://www.someWebsite.com/web/scripts/jquery/jquery.js:9260:15)
at HTMLScriptElement.jQuery.ajaxTransport.s.send.script.onload.script.onreadystatechange (www.someWebsite.com/web/scripts/jquery/jquery.js:9831:8)
The control reaches the JsonpSuccessCallBack method and through ajaxconvert() meth in lib file, then throws an error. I Cant get why this error is thrown.
I have googled a lot for this issue and followed the steps mentioned but cant fix this,Can anyOne please help me to Fix this issue..
Thank You in advance :-)
I use this code to get some information from twitter via their api:
$.ajax({
url : apiUrl,
cache : false,
crossDomain: true,
dataType: "jsonp",
success : function(html) {
// ...
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
}
});
However, if the apiUrl variable provides a correct url, this code work fine, e.i. the success object is executed, but if the url isn't correct, e.i. 404 error is returned from twitter, the error object is never executed. It doesn't log anything in console. How should I check for 404 error status in this case?
From jQuery API ajax docs:
error option
Note: This handler is not called for cross-domain script and JSONP
requests.
http://api.jquery.com/jQuery.ajax/
According to the docs, use statusCode setting in .ajax.
$.ajax({
...
statusCode: {
404: function(){
}
}
});
I'm using jQuery 1.2.6 (I know it's old, but I don't have a choice) I need to check the status of my ajax calls. I either want to use:
statusCode, or I could even use error(jqXHR, textStatus, errorThrown), except that textStatus, errorThrown and statusCode, aren't in my jQuery version.
Basically what I have to do, is know if the ajax call was aborted, or had an error for another reason. Any ideas how I can do this?
you could get the status text from the error callback:
$.ajax({
url: "/foo",
dataType: "text",
error: function(obj){
alert(obj.status + "\n" + obj.statusText);
}
});
http://jsfiddle.net/jnXQ4/
you can also get it from the complete callback if the request resulted in an error.
Edit: the ajax request also returns the XMLHttpRequest which you can then bind events to, though I'm not sure how cross-browser it is.
var request = $.ajax(options);
request.onabort = function(){
alert('aborted');
}
I am using the following code to retrieve data in JSONP format. I need to use it so if no data is returned, I can flag the error. I was using jQuery's ajax(), but it always returns 404 pages as being successful, so I need to use the jquery-jsonp jQuery plug-in on Google Code for error handling.
I borrowed the code from the example on jQuery ajax (jsonp) ignores a timeout and doesn't fire the error event, but I cannot seem to get it to work with my JSON, which is being sent as the MIME type "application/json" from the other server.
$(function(){
var jsonFeed = "http://othersite.com/feed.json";
$.jsonp({
url: jsonFeed,
dataType: "jsonp",
timeout: 5000,
success: function(data, status){
$.each(data.items, function(i,item){
console.log("Title: " + item.title);
if (i == 9) return false;
});
},
error: function(XHR, textStatus, errorThrown){
console.log("Error Status: " + textStatus);
console.log("Error Thrown: " + errorThrown);
}
});
});
Here is an example of my JSON:
[ { "title" : "My Title" } ]
Can anyone spot the problem?
Are you sure "othersite.com" actually supports JSONP. JSON cannot be converted to JSONP by the client. The server needs to support it be wrapping the content with a callback function.