Jquery Ajax call return 403 status - javascript

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.

Related

Ajax call returning HTTP 302

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");
}
});
}

What HTTP response codes does the jQuery aJax error handler consider an 'error'?

I have a standard aJax call back to the server:
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json',
url: '/Apps/ResetDateAndCount',
data: JSON.stringify({
appName: app
}),
success: function (response) {
$('.lastReset').text(response);
$('.currentCount').text('0');
},
error: function (xhr, status, error) {
alert("You are not authorized to perform that action");
}
});
From my server (ASP.NET) I am returning errors like:
return Json(new { success = false, error = "You are not authorized to perform that action" });
and
Response.StatusCode = 401; return Json(new { success = false, error = "You are not authorized to perform that action" });
and
Response.StatusCode = 500; return Json(new { success = false, error = "You are not authorized to perform that action" });
Inside of the error handler error: function (xhr, status, error) only the last return will be caught as an error, when the status code is set to 500.
I am wondering what response codes aJax actually consider an "error"?
Any error code that is outside of the interval [200, 299] and different than 304 is considered an error by jQuery when making an AJAX call.
Now of course you're gonna ask me, that's fine and dandy but why the hell this is not considered as an error, after all I am returning 401 which outside of the aforementioned interval so it should be considered an error:
Response.StatusCode = 401;
return Json(new { success = false, error = "You are not authorized to perform that action" });
Very simple: because when you return a 401 status code from a controller action in ASP.NET MVC, the framework (and more specifically the ASP.NET Forms Authentication module) will intercept this request and redirect you to the login form eventually resulting in a 200 status code. Yeah, the login page is served with a 200 OK status code. In this case 200 is inside the interval so no error callback is invoked. You can validate this by inspecting the DOM of the login page returned in your success callback for this particular case.
Now put yourself into the perspective of a browser making an AJAX request: It will follow all the redirects that a server makes until it reaches the final destination. If this final destination status code is outside of the interval and different than 304 then you will get the error callback invoked. OK, now things start to make a little more sense.
So the next question you're gonna ask me is how do I invoke the error callback if I return a 401 status code from my controller action, right? Then I will redirect you (:-)) to the following blog post: Prevent Forms Authentication Login Page Redirect When You Don't Want It.
I would suggest checking the list of standard HTTP codes. Please see it here https://en.wikipedia.org/wiki/List_of_HTTP_status_codes. It's self-explanatory.
In other words, any codes >= 400 (4xx, 5xx) can be considered as an error.
You are returning the error message:
"You are not authorized to perform that action"
I'd say, this text message corresponds mostly to 401/403 codes. For 5xx errors, I would suggest you display some server error message.

Prevent IE10 from Redirecting to Login Page After 401 Error on AJAX Call

I have the following javascript code that performs a POST to an API for a login page:
do_post_form_data = function (relative_url, access_token, postData) {
return $.Deferred(function (def) {
$.ajax({
type: 'POST',
url: baseURL + relative_url,
contentType: 'application/x-www-form-urlencoded',
dataType: 'json',
data: postData
})
.done(function (data) {
def.resolve(data);
})
.fail(function (jqXHR, textStatus, errorThrown) {
var error = jqXHR.responseJSON ? jqXHR.responseJSON : { error: "", error_description: "POST failed." };
def.reject(error);
});
});
},
If the login fails (invalid credentials are sent), the API returns a 401 Unauthorized error to the caller with a JSON object in the body explaining why the login failed. The code works as expected when sending the data from the latest versions of Chrome, Firefox and Safari. The responseJSON object exists on the jqXHR object, and I can retrieve the error messages.
However, IE10 seems to be intercepting the 401 error and trying to redirect to a login page, for which the API server does not provide a URL, though I cannot see any additional calls being made to the server in Fiddler. My AJAX call never sees the 401 error but winds up receiving a 404 error with no JSON data in the jqXHR object.
Has anyone seen this behavior before and found a way to make IE report the initial 401 error to the AJAX call? IE10 with jQuery 2.0.2.
Thanks for any suggestions.

Salesforce - success handler for $.ajax call

I have a form that I have been submitting to Salesforce with standard form submit action. By default, you can tell Salesforce to redirect you to a given URL after the POST has completed.
I no longer wish to be redirected since I have other activities on the form page. No problem, my page is already using jQuery so I can use the handy $.ajax utility like this:
$('#wrapper').on('click', '#formsubmit', function(e) {
e.preventDefault();
var formData = $('#subForm').serialize();
$.ajax({
type: "POST",
url: "https://www.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8",
data: formData,
success: function() {
console.log('success!'); // or not!
},
error:function (xhr, ajaxOptions, thrownError){
console.log(xhr.status); // 0
console.log(thrownError); // empty
}
});
});
In my misguided brain, I imagined that Salesforce would return my good ol' redirect, which would count as a "success" that I can just discard/ignore. Misguided indeed!
I can see a 200 OK result (which usually means "success") but the success callback isn't tripped.
The lead is added to the Salesforce database
Inspecting the content of what's returned shows zero; there is no content in the response.
The error callback IS being tripped (despite the 200 OK) but maybe due to intentionally not redirecting it is seen as a "resource not available"? (therefore my status code is 0, and there is no content in the thrownError?).
Any advice on identifying this as a successful POST so that I can trigger additional actions in a callback? I don't want to TOTALLY ignore the response, or I could end up in a scenario in which I'm acting on a failed POST as if it was successful. I need to capture the success somehow.
It occurred to me that it could be a cross-site scripting issue as well, but since the application doesn't exchange data in JSONP, I'm not sure how to get around that (and I'm not sure how to identify it in the first place).
Few things here:
1) The redirect response being sent by salesforce's API is most likely being interpreted as an error code.
2) The response code of the subsequent page (after the redirect) is 200 OK, from the sound of it.
3) It is not possible to do a POST request using JSONP. This is a limitation of JSONP; which is not actually an AJAX request, but an HTTP GET request wrapped inside of a dynamically generated script tag. Also, JSONP only works if the request yields an HTTP response of 200 OK.
I would recommend using your own server-side intermediary to handle your AJAX POST request. This will act as a proxy between your front-end app and salesforce's API. This will also allow you to better control the response being sent to your app.
var formData = $('#subForm').serialize();
var response = $.ajax({
type: "POST",
url: "https://www.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8",
data: formData,
success: function() {
console.log('success!'); // or not!
},
error:function (xhr, ajaxOptions, thrownError){
console.log(xhr.status); // 0
console.log(thrownError); // empty
}
}).responseText;
where var response will contain the return value from your ajax call

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