Ajax call returning HTTP 302 - javascript

When we make this ajax call, intermittently I get HTTP status code as 302. While most of the times, the ajax call is successful as well returning HTTP status as 200 OK. I am unable to get the exact reason for this and how to overcome this scenario.
The HTTP status 302 is returned in particular scenario when I leave the application idle for 10-15 minutes and then make this call.
However when I hit the URL directly in browser the correct data is returned.
Please advice.
function checkProgressStatus(event){
$.ajax({
url: "/"+window.AppContext+"/servlet/Progress",
cache: false,
dataType: 'json',
async:false,
success: function(data,ev){
if(data.Progress == 'INPROGRESS'){
alert("Execution in progress");
event.stopImmediatePropagation();
}
},
error: function (exception) {
alert("Request to check inprogress status failed.");
window.open("/"+window.AppContext+"/path/filter/AnotherPage.html");
}
});
}

Related

Error or fail not being reached when Ajax fails to fetch JSON

I am working on below Ajax code in JavaScript, I am trying to pop up a dialog box when the URL could not load the JSON properly the reason may be either expired token or incorrect token, in any case, I am expecting the code to hit the error or fail but it's not happening. When the URL could load the JSON successfully, success and complete blocks are being hit as expected but nothing is being hit when URL fails. I have tried to use async: false and tried to check with a boolean variable weHaveSuccess but console.log(weHaveSuccess); which is in the last line of the code is getting executing even before success/error is being executed and it seems to me like its still loading asynchronously. I would like to know why error block is not being hit when the JSON load from URL is getting failed.
My code
function checkUser(myURL, newAccessToken, weHaveSuccess) {
$.ajax({
type: "GET",
dataType: "jsonp",
async: false,
url: myURL + newAccessToken,
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("Status: " + textStatus);
console.log("Error: " + errorThrown);
},
success: function (data) {
console.log("Hello 2 " + JSON.stringify(data));
weHaveSuccess = true;
console.log('Message from Success ' + weHaveSuccess);
},
complete: function () {
console.log('Message from Complete ' + weHaveSuccess);
}
}).done(function (data) {
alert("Success");
console.log(data);
}).fail(function (data) {
console.log(data);
alert("Failed");
}).always(function () {
alert("In Always");
});
console.log(weHaveSuccess);
}
Thanks in advance!
AJAX requests are asynchronous. It takes time for a remote request to be made and responded to. You will have to write your post-response code within the success function or call another function from there, not within the same scope as where the call is initiated.
I am taking a bit of a guess here about what your server returns on failure. An AJAX request success means simply that a 200 OK response was received, without any consideration of the contents of the data. If an error is simply a change in the data you will need do one of the following to show an error:
Have the server set a status code header on failure, perhaps 400 Bad Request.
In the success function look within your data for whatever error response you are expecting and trigger the alert() there.
First of all the console.log(weHaveSuccess); fires first, because the $.ajax() is asynchronous while console.log is not so ajax will be triggered and return the promise when finishes, but the browser will continue with the script.
In the jQuery ajax docs says:
Cross-domain requests and dataType: "jsonp" requests do not support
synchronous operation.
It's hard to debug without seeing the response, maybe you can add some info from the network or a URL?
How about if you try the following:
Add the jsonp setting to your $.ajax() function for the callback that will handle the response and console.log there:
function myCallback(data) {
console.log(data);
}
$.ajax({
type: "GET",
dataType: "jsonp",
jsonp: myCallback,
...

Jquery ajax response not calling Success method

I am pretty much new to ajax and working on jquery ajax request. Ajax callback is not calling success method. Interaction is between cross-site domains.
My AJAX request looks like
$.ajax({
timeout: 20000,
url: 'test.com',
crossDomain: true,
dataType: 'jsonp',
success: function (data) {
console.log('callback success');
this._cache = data;
localStorage.token = data.access_token;
} });
There are no errors in this call.
This ajax request is not calling success function.Request is returning json data. it's just success method is not getting called.
This ajax request is not calling success function.
Get request is getting fired successfully. I can even trace the response in fiddler with 200 http response.For some reason success method is not getting called.
it's returning json object, which I've traced in fiddler
You're telling jQuery to expect a JSONP response, so it is trying to execute the JSON document as if it were a JavaScript script (because that is what JSONP is). This fails because it is not JSONP.
Either return JSONP instead of JSON or (assuming the server returns the correct Content-Type) remove dataType: 'jsonp',.
ok... I came here with the same problem... and when I read that specifying datatype:jsonp never calls success as a callback per #mondjunge from a comment above, it started me thinking about some behavior I saw earlier from my code and that maybe datatype:json might have the same behavior for what ever reason here too.
So after reading this page I took out my datatype declaration from my ajax request and my servlet returned the proper data payload, returned a 200, and jquery called the success function finally and modified my DOM.
All those steps happened except the last one until I removed my datatype from my ajax call. NOT what I was expecting!
Hopefully someone else can shed some light on why this happens... for now at least the few that don't lose their minds to this issue that find this post can do this in the mean time.
Check if your ajax is executed
Check it's status. If response code is != 200, than you should add error method also, for error handling.
Try this:
$.ajax({
timeout: 20000,
url: 'test.com',
method: 'GET',
crossDomain: true,
dataType: 'jsonp',
success: function (data) {
console.log('callback success');
this._cache = data;
localStorage.token = data.access_token;
},
error: function(xhr, error){
console.debug(xhr); console.debug(error);
},
});

Jquery Ajax call return 403 status

I have a jquery Ajax call implemented for keepalive the session, this keepAlive() method will call in every 20 mins
function keepAlive() {
$.ajax({ type: "POST",
url: "KeepAliveDummy.aspx", cache: false
});
}
This call is happen when the third party contents are loaded in to the frameset,
I'm getting 403 http status (check via fiddler) on this request,
Will this impact the end result of refresh the session time out?
Since your question is about handling 403 error (Will this impact the end result of refresh the session time out?) rather what 403 is.
So, handle this error, you can log or notify.
$.ajax({
type: "POST",
url: "KeepAliveDummy.aspx",
success: function (response) {
//session refreshed
},
error: function (xhr, ajaxOptions, thrownError) {
if(xhr.status==403) {
//handle error
}
}
});
about 403 :
403 Forbidden The request was a valid request, but the server is
refusing to respond to it.[2] Unlike a 401 Unauthorized response,
authenticating will make no difference.[2]
it needs you to authenticate (like login) first before do call ajax. 401 error requires authenticating header field when request but 403 doesn't.
check your server or contact who has responsibility for authentication.

Ajax call fires error event but returns 200 ok

$.ajax({
url: 'http://intern-dev01:50231/api/language',
type: 'GET',
dataType: 'json',
success: function() {
console.log('It Works!');
},
error: function (request,status, error) {
console.log(error);
alert(status);
}
});
Why do this ajax call not work ?? if i call in browser it works fine :/.
This is what fiddler returns:
HTTP/1.1 200 OK
Content-Length: 122
Content-Type: application/json; charset=utf-8
Server: Microsoft-HTTPAPI/2.0
Date: Fri, 26 Apr 2013 06:56:40 GMT
[{"LanguageId":1,"LanguageName":"Dansk"},{"LanguageId":2,"LanguageName":"Tysk"},{"LanguageId":3,"LanguageName":"Engelsk"}]
You have to check ajax response if it is valid or not. When you specify in ajax:
dataType: 'json',
jQuery will fire the error event if the response cannot be parsed as JSON, even if server returns 200 OK. Check the data returned from the server and make sure it is valid JSON (try JSONLint service).
If the returned data is not JSON or it has syntax errors then fix them in your server side code. You can just return {} from the server side script.
Also try this.
$.ajax({
url: 'http://intern-dev01:50231/api/language',
type: 'GET',
cache: false,
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
console.log(error);
alert(status);
}
else {
console.log('It Works!');.
}
}
});
There is a parsing error since the status shows 200 OK. The problem lies in the datatype:json. To test this, remove the line and it should work. In order to fix this, you can change it to the datatype:text. See this link too for similar question
Check the url parameter and make sure its the same as the loaded page. You might be doing a cross-domain ajax call. If you were wanting to make a cross-domain ajax call, notice that the only dataTypes allowed to make cross-domain requests are "script" and "jsonp".
Ran into this issue in a dev environment where the URL was an IP address and the page loaded a domain-name pointing to that ip.
I know I'm a little late, but I just ran into the same problem and this is one of the top search results on Google. I managed to fix it by moving datatype above url like this:
$.ajax({
type: 'GET',
dataType: 'json',
url: 'http://intern-dev01:50231/api/language',
success: function() {
console.log('It Works!');
},
error: function (request,status, error) {
console.log(error);
alert(status);
}
});
If you are testing locally with a different web app and web API applications , then debug your application and test API send data correctly and app calls to API via AJAX and return data.
since domains are not similar when run application AJAX call doesn't hit to success function. because browser prevents Cross Site request. If you publish both app in local and debug , it's work fine.
hope this would be helpful someone.

jQuery ajax - Absolute URL's and error handling

Is it possible to catch the HTTP errors (like 404, 500, 504 etc) when we call an external webservice by specifying an absolute url?. (like setting the url: attribute of $.ajax call to have a url value as http://api.geonames.org/findNearbyPostalCodes.
Right now I'm unable to receive any errors although firebug is catching them and showing it in the console.
Can someone help?
Here is my code.
$.ajax({
type: 'GET',
url: "http://api.geonames.org/findNearbyPostalCodes",
data: '{"lat":47,"lng":"9","username":"demo"}',
dataType: 'json',
cache:false,
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);
}
error: function (xhr, exception, thrownError)
{
alert(xhr.status);
}
});
No, it is not possible with cross-domain (external) requests using only client-side code. This is because cross-domain requests rely on JSONP - ie, injecting a script tag that loads code from an external source. Unfortunately, the <script> element does not have anything like an onerror event.
You can handle errors with same-domain requests because these typically use XMLHttpRequest, which returns a lot of useful information like status codes and response headers.
Your best bet would be to use your local server as a proxy.
If using an absolute URL causes the domain to be different from the domain of your page (cross-domain request), then the only way to successfully execute an ajax call is to use JSONP which will cause the ajax library to use <script> tags for the cross-domain request instead of the more typical XMLHttpRequest used for same-domain requests.
You will not be able to intercept any sort of status codes from the loading of the cross-domain <script> tag.
In your case, you cannot check the status code (assuming you're not making the request from api.geonames.org).
jQuery will always return a "0" as the status if the request is cross-domain:
$.ajax({
type: 'GET',
url: 'http://someotherdomain.com/api/query',
dataType: 'json',
data: '{"first": 1, "second": 2}',
complete: function(response) { // the 'response' object has the status code
if (response.status == '200') {
// do something on success
} else if (response.status == '0') {
alert('Your request is cross-domain');
}
}
});
If the request happens to be within the same domain, you'll get a valid status code that you can check (the complete attribute of the $.ajax() function will run after any success or failure callbacks are run).

Categories

Resources