Automatic redirection on 302 status - javascript

$.ajax({
type: "POST",
url: "/someurl",
data: $("#send_application_number").serialize(),
success: function(response, textStatus, request) {
#responseType = request.getResponseHeader('Location')
$("#captchapopup").foundation("reveal","open")
$("#viewstate").val(response['viewstate'])
$("#eventvalidate").val(response['eventvalidate'])
$("#appl_num").val(response['appl_num'])
#loc = getcaptchaimage(response['viewstate'], response['eventvalidate'])
loc = '/anotherurl?viewstate=' + response['viewstate'] + '&eventvalidate=' + response['eventvalidate']
$("#captchaimage").attr('src', loc)
},
error: function() {
alert("Could not get response to session login request");
}
});
As you can see this is a script for running a modal pop-up to display a captcha. BUT, I may redirect to another url as well, instead of displaying the modal, which is why I sent a 302 redirect (and a url of course) from back-end assuming it would redirect automatically. It did , BUT the rest of the script also executed as well, which brought it back to the modal.
How do I achieve an if-else kind of redirect? That if 'Location' is present, redirect and don't execute the rest of the script?

AJAX is a request in the background, and that means you can not redirect the “foreground” (browser UI) from there via HTTP.
Use location.href="…" to redirect from within your success handler. (Have your server send it a value that it can base that decision on.)

Related

How to redirect a user to a login page from a servlet? [duplicate]

This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 5 years ago.
I am trying to redirect a user to the login page of the website from page A if at the time of the page load no login details are found in the session. I am using a servlet for the same.
From page A, I am making the most basic AJAX call at page load to my servlet as below:
$.ajax({
url: "/bin/website/protectedpage.html",
success: function(){
}
});
However, I have only been able to achieve the following results with the mentioned approaches:
1.
response.sendRedirect("/content/website/en/login.html");
resulting into an HTTP code 302 in response but no redirection actually happening. Also, there is nothing returned in the response body.
2.
ServletContext context= getServletContext();
RequestDispatcher rd= context.getRequestDispatcher("content/website/en/login.html");
rd.forward(request, response);
resulting into a Response code 200 returning the whole login page HTML in the response body but still not redirecting the user to the login page.
What am I missing? Please help me with the same. Thanks in advance.
$.ajax() performs an asynchrounous HTTP call to the server. Redirecting the call just from the server won't also redirect on the browser. You will have to handle the redirection after the ajax call on the front-end itself.
You can try something like this
$.ajax({
type: "POST",
url: URL,
data: reqBody,
dataType: "json",
success: function(data, textStatus) {
if (data.redirect) {
// Redirect here
window.location.href = data.redirect;
}
else {
// No redirection.
}
}
});
PS: Code block copied from here.
you can use window.location.replace("url") (simulate an HTTP redirect).
If ypu prefer, you can use window.location.href = "url". This is similar to click a link.
The function replace() does not keep the originating page in the session history, so the user can't get stuck in a never-ending back-button. For me, replace() is the best choice.
Would you have tried something like
function_name(funct) { return function(data) { if($("#myForm", data).size() > 0) top.location.href="login"; else funct(data); } }
for example
function sample(data, funct){
if($("#myForm", data).length > 0)
top.location.href="login.htm";//redirection
else
funct(data);
}
Then, when making the Ajax call we used something like:
$.post("myAjaxHandler",
{
param1: sam,
param2: kari
},
function(data){
sample(data, myActualCB);
},
"html"
);
all Ajax calls always returned HTML inside a DIV element that we use to replace a piece of the page. Also, we only needed to redirect to the login page.
We basically have an ISA server in between which listens to all requests and responds with a 302 and a location header to our login page.
Now check for status 302 as you have mentioned above that you are getting response 302
$(document).ajaxComplete(function(e, xhr, settings){
if(xhr.status === 302){
var loginPageRedirectHeader = xhr.getResponseHeader("LoginPage");
if(loginPageRedirectHeader && loginPageRedirectHeader !== ""){
window.location.replace(loginPageRedirectHeader); //check for location header and redirect...
}
});

Using window.location.replace after an Ajax response does not redirect immediately

I am implementing facebook connect for authentication. I also want to verify that the email of the user I receive from facebook matches with an internal database (essentially invite list). So I use an ajax call as below. However, the redirect does not happen immediately. The user needs to refresh the window in order to get redirected. Any ideas why and how this can be fixed? Thanks!
Note that this happens within FB.api which in turn is inside window.fbAsyncInit.
$.ajax({
type: "POST",
url: "verifyLogin.php",
data: ("email=" + myEmail),
success: function(resp){
if (resp == 'success')
{
window.location.replace('/index.php');
}
},
error: function(e){
alert('Error: ' + e);
}
});
This should be immediately after the request has returned success have you tested that the response occurs immediately if you are not inside the facebook window class?
also the resp check should not be necessary if you are not returning the word "success" from verifyLogin.php
Tell us more about what you mean about immediately.

Jquery cross site Ajax call with 302 success data undefined with datatype script otherwise return error

I'm using JQuery 1.7.2, trying to do a cross site Ajax request which should return a html page via 4 redirects.
Not my ideal world with all those redirects, but it's part of the specification.
Now, using the following code:
$.ajax({
type: "GET",
url: myUrl,
dataType: "script",
success: function(data) {
alert("success :"+ data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("revoke: "+textStatus + ' / ' + errorThrown+"/"+jqXHR.status);
},
complete: function(jqXHR, textStatus){
alert("complete : "+jqXHR.statusText + ": "+jqXHR.readyState);
}
});
I can see in Firebug/Safari Developer Tools, that all the redirects work (e.g. returns a 302 status with a Location header).
Then the strange thing happens: At the last page, which returns a 200 status, my script ends and I try to view the data coming back. But the output is just "Undefined".
I agree on that I should not expect a script datatype when trying to get a html page, but when I tried with all the other datatypes (as defined in the jquery ajax page), the error handler is envoked and the status code is 0. All the while, in Safari DT, the status after the first redirect is just set as "(canceled)" (all the while the request just for the second redirect page just hangs in Firebug - but I'm just guessing that it has to do with their different implementation).
When I receive a 200 status, I can see in the debuggers that the last page has a size of some 18kb, which means that there should be some sort of data in it.
what to do?
You can't redirect with AJAX, you can only send and get data to and from the server.
For a redirection you have to use a "regular" HTTP request.
It can also be done with javascript window.location = myUrl

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.post() and redirect via ajax

I am using jQuery.post() to send data to the server, when the server sends data back to the client, the post() callback is invoked. I know that the server might response with the redirect header field ("Location").
currently, the redirect does not occur. what can be the reason?
is there any possibility to run a script before the redirect occur?
UPDATE:
enclosed a snipped code. i know that the POST method is accepted by the server, and that the server responds to the POST. somehow, always the error() is being invoked (it seems like it happends even before the response is accepted by the client\browswer).
what is wrong?
$(document).ready(function() {
$("#loginForm").submit(function() {
$.ajax({
type : "POST",
data : $("#loginForm :input").not("#loginBtn").serialize(),
url : "http://localhost/auth",
success : function(data, textStatus, jqXHR) {
alert("success");
alert(jqXHR.getResponseHeader("Location"));
},
error : function(jqXHR, textStatus, errorThrown) {
alert("error");
}
});
});
});
jquery.post() works by issuing an Ajax request. In an Ajax call, the PHP script works asynchronously (think of it as a background thread). Thus, the PHP script cannot redirect the client's browser. The way to go would be to have the PHP script responsd with the URL to redirect to, and redirect using javascript.
In your POST callback:
function(data){ //data will be the URL to redirect to, sent back by the PHP script
window.location = data;
}
EDIT
From Jquery documentation on jquery.ajax()
statusCode(added 1.5)Map
Default: {}
A map of numeric HTTP codes and functions to be called when the response has the corresponding code. For example, the following will alert when the response status is a 404:
$.ajax({
statusCode: {
404: function() {
alert('page not found');
}
}
});
If the request is successful, the status code functions take the same parameters as the success callback; if it results in an error, they take the same parameters as the error callback.
Please in redirect case get simple response without redirecting print any flag like "redirect" and and write client side redirect using
if(responce == 'redirect')
window.location = "Your url"
Do not redirect on server.
It will work.
If you perform an operation that results in a redirect, JQuery does not detect it. The browser handles it automatically behind the scenes, to create a seamless experience.

Categories

Resources