I have a requirement to clear the cookies and to redirect to a new url after clicking on a link. I wrote the below code which calls "logOffRedirectUrlForCookieDeletion" which is responsible to clear the cookies and redirect the application to the homepage and "myUrlAfterCookirDeletion" is the new url that needs to be redirected from the homepage after cookie deletion. If I use any one of the "window.location.href" statements, my code works absolutely fine but if I use two "window.location.href" statements only the second one is getting executed. Can someone please suggest me how to use 2 url redirection using window.location.href
ClearCookiesAndRedirect:function(redirectURL){
if (confirm("Do you want to leave the website?") == true) {
window.location.href = logOffRedirectUrlForCookieDeletion;
window.location.href = "myUrlAfterCookirDeletion";
} else {
return;
}
},
Add an iframe to delete cookies. That would load the cookie deletion page + not redirect, after that redirect:
iframe=document.createElement("iframe");
iframe.src="cookiedeletion.html";
iframe.onload=function(){
//cookies deleted lets redirect
window.location.href="newurl";
};
document.body.appendChild(iframe);
However, why not delete the cookies right on the page? Much easier...
I have my oauth2 for Gmail open up in a popup using newWindow = window.open(...) and then when the user is done filling it out and hit 'allow' it redirects to my server where the tokens are retrieved and stored. Finally, the server returns 'Error' or 'Success' so the popup will just have that in it. Now on the Angular side I have this running.
checkConnect = setInterval(function() {
try{
if(newWindow.document.body.innerText === 'Success') {
console.log('Success');
newWindow.close();
window.clearInterval(checkConnect);
}else if(newWindow.document.body.innerText === 'Error') {
console.log('We had an error!');
newWindow.close();
window.clearInterval(checkConnect);
}else if(newWindow.closed) {
console.log('WINDOW WAS closed');
window.clearInterval(checkConnect);
}
}catch(e) {
//console.log(e);
}
}, 100);
This works sometimes and other times it fails. I also reuse this code for other Oauth providers, such as Dropbox.Sometimes it works and sometimes it doesn't. Any idea why?
Well I couldn't figure it out by using a popup. However, I was able to over come this problem by just having the oauth page open in the same page and redirect back to the page I wanted the user on afterwards.
Also, there are libraries provided by google that open it for you in a popup and handle the closing.
Without ajax, if we load http://example.com/1 and if it redirects to http://example.com/2 then the browser gets appropriate headers and the Browser URL get's updated. Is there a way to get this information via jQuery Ajax?
For example, I am requesting http://api.example.com via Ajax. In PHP, this page is redirected to http://api2.example.com. Is it possible to know this thing?
Use:
I have a navbar which has links. All pages are loaded into the container via AJAX and I push the url on Browser Bar using HTML5 history as per the link.
However, if the page gets redirected, the page would have a new link right? I would like to change that in the Browser bar too. I would like to know where the Ajax URL is redirected in case it is redirected.
Why this is important?
My links handle form data, requests and various authentications. For example, if I request, https://oauth.example.org?code=56hycf86 it either redirects to success or failure page. My Ajax get the right html content but the URL browser bar still has the URL with same Auth ID which, if reloaded, produces error. There are other security issues too.
I do not know if I explained things right, but thanks for your help.
Well, unfortunately, ajax always follows redirects. However, there is a feature that is not supported in all browsers, you can access the responseURL property of the XMLHttpRequest object.
You can try it in the below code snippet. the redirect button sends ajax request to a URL that replies with 1 redirect (it also works if there are multiple redirects).
The no redirect button sends ajax request to a URL with no redirects.
As far as I know this method is not supported in IE 11 and older versions of chrome/firefox/opera browsers.
document.getElementById("no-redirect").addEventListener("click", function() {
testRedirect("https://httpbin.org/get");
});
document.getElementById("redirect").addEventListener("click", function() {
testRedirect("https://httpbin.org/redirect/1");
});
function testRedirect(url) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(e) {
if (xhr.status == 200 && xhr.readyState == 4) {
if (url != xhr.responseURL) {
alert("redirect detected to: " + xhr.responseURL)
} else {
alert("no redirect detected")
}
}
}
xhr.open("GET", url, true);
xhr.send();
}
<button id="redirect">
Redirect
</button>
<button id="no-redirect">
No Redirect
</button>
This might not be exactly what you're looking for, but maybe it will help you get a similar effect.
If you are in control of what the page http://api.example.com does, you could change the way it reacts when it gets a call via AJAX.
You could include a variable in your AJAX call, marking it as such a call, and if this variable is present, not redirect to an other page, but include the URL it would redirect to, in the answer.
The data returned in the AJAx call could be a hash, in which one key represents the redirect url.
data = {status => 1, redirect => 'http://ap2.example.com', …}
(Sorry if that is not a valid PHP hash)
not sure if I understood it, but just tried something, if it is not what you're looking for please notify me to delete the answer.
here we inject this /#/ in the URL so when clicking on links the browser will have a new segment in the URL which represent the parameter that depending on its value you can determine which page to load using the corresponding AJAX call..
JS/jQuery:
var navLinks = $('#nav a'),
params = [],
baseURL = '//localhost/test/js-url-parameters-second';
navLinks.each(function(){
var oldHREF = $(this).attr('href');
$(this).attr('href', baseURL +'/#/'+ oldHREF);
});
navLinks.on('click', function(){
checkURL($(this).attr('href'));
});
function checkURL(docURL){
// if /#/ found then we have URL parameters
// grabbing the parameters part of the URL
if(docURL.indexOf('/#/') > -1){
docURL = docURL.split('/#/')[1];
if(docURL != ''){
// omit the last forward slash if exists
if(docURL[docURL.length - 1] == '/'){
docURL = docURL.substring(0, docURL.length - 1);
}
console.log(docURL);
$('#page-type').text(docURL);
}
} else {
console.log('No URL parameters found');
}
}
HTML:
<div id="nav">
Home
About
Contact
</div>
<hr>
<div id="container">
this is the <span id="page-type">Home</span> page
</div>
As the already mentioned responseURL doesn't have the best browser support yet, there are 2 more alternative for this case that could be used, http request headers and cookies.
The benefit with these is they don't interfere with the content itself, like for example query string keys, hash tags or embedded in the response data.
Request headers
Server side
PHP
$req->addHeader("X-Response-Url", "....");
ASP
headers.Add("X-Response-Url", "....");
Client side
xhr.onreadystatechange = function(e) {
if (xhr.status == 200 && xhr.readyState == 4) {
var resp_url = xhr.getResponseHeader("X-Response-Url");
if (send_url != resp_url) {
// redirected
}
}
}
Cookies
PHP
setcookie("XResponseUrl", "...");
ASP
Response.Cookies("XResponseUrl") = "..."
Client side
xhr.onreadystatechange = function(e) {
if (xhr.status == 200 && xhr.readyState == 4) {
var resp_url = getCookie("XResponseUrl");
if (send_url != resp_url) {
// redirected
}
}
}
function getCookie(name) {
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
Yes, when you request http://api.example.com using Ajax, browser does not redirect. You can get all the response using jQuery like bellow
$.ajax({
url: "http://api.example.com",
success: function(data, textStatus, xhr) {
console.log(xhr.status);
},
complete: function(xhr, textStatus) {
console.log(xhr.status);
}
});
I am using a login system for my website.
What I am doing is that when the user clicks the submit button an ajax request is being executed to target php script which logs in the user and if user is logged in successfully then echo's back the message "login_successful" to the ajax request. By using if statement I check whether the message is "login_successful" else display the error.
If the message is "login_successful" the script redirect the user to the new page 'user.php' by using window.location = 'user.php';
//I have also tried this.
window.location.href = 'user.php';
But it doesn't work It simply stays on the login page and nothing happens.
but when i check the page source after logging in but no redirection takes place then i got a surprise that the source of the page is for user.php instead of login.php. Somehow window.location hasn't redirected the page but bring the source of user.php to login.php. It's all messed up and I couldn't solve the problem.
Here is the login function which performs the ajax request and then redirect the user-
function login()
{
var e = _("email").value;// Grab the email input by the user.
var p = _("password").value;// Grab the password input by the user.
if(e === "" || p === "")// Check if they are empty.
{
_("status").innerHTML = "Fill out all the form data";//Display error message if fields are empty.
}
else
{
_("loginbtn").style.display = "none";// Hide the login button
_("status").innerHTML = 'please wait ...';//Tell the user to wait while the script works.
// Below id another function which is defined in other js file.
var ajax = ajaxObj("POST", "login.php"); //start the ajax request.
ajax.onreadystatechange = function()// Wait for the request to be complete
{
if(ajaxReturn(ajax) === true) // Ensures if the response is recieved
{
var response = ajax.responseText;// Put the response in a variable
if(response === 'login_successful')// Check if user is logged in succesfully.
{
window.location = 'user.php';//Redirect the user to the new page.(Not working)
}
else
{
_('status').innerHTML = response;// Display the response
_("loginbtn").style.display = "block";// Display the login button
}
}
};
ajax.send("e="+e+"&p="+p);
}
}
I am using the latest version of chrome on a 64 bit windows machine.
Update
OK guys I have verified that the response via php script is 'login_successful' and it doesn't contains any line so that we can trim on it.
check the result by alert in between response condition & use
window.location.href='correctfilepath.php';
correct path of file to be redirected. Check your user.php also as it will not print anything if it will have some error in code
if you use location i prefer to use a absolute path. Maybe this is your problem and a redirect will be working with this. For example:
location.href = '/user.php';
If you want to redirect to a url do it like this:
location.href = '//www.google.com';
(it will automatically use http or https based on the current scheme.
Try setting the full URL for redirection
window.location = window.location.protocol + "//" + window.location.host + "/user.php"
instead of window.location = 'user.php';
Edited:
window.location = "//" + window.location.host + "/user.php"
Javascript redirection works without the protocol (http or https) also.
if(response === 'login_successful')// Check if user is logged in succesfully.
{
window.location = 'user.php';//Redirect the user to the new page.(Not working)
}
else
{
_('status').innerHTML = response;// Display the response
_("loginbtn").style.display = "block";// Display the login button
}
In the else block you had given _('status').innerHTML = response; check that block is executing or not if its is executing then try to change the (=== as == )in the if condition hope it may work.
I need to use JavaScript (jQuery if applicable) to trigger my modal call if the result of my function is true and the referring URL is not of the domain.
The desire is that the user visits the main splash page and as long as they have not been redirected there by the site itself (via timeout on a session, invalid login credentials, etc) it displays the message so:
function showModalIf() {
if (checkFunction) {
if(////// REFERRING URL not from this site)
Trigger Modal Call
else
Don't Do anything else
}
}
Assuming you use jQuery UI Dialog to show the modal
function checkReferrerExternal() {
if (!document.referrer || document.referrer == '') return false;
var regex = /^https?:\/\/\/?([^?:\/\s]+).*/;
var referrermatch = regex.exec(document.referrer);
var locationmatch = regex.exec(document.location);
return referrermatch[1] != locationmatch[1];
}
function showModalIf() {
if (checkReferrerExternal()) {
//show jQuery UI Dialog modal or replace with whatever
$("div#dialog").dialog('open');
}
}
Check demo page http://jsbin.com/efico
If you are talking about forced redirection in the code, and not just a hyperlink click from elsewhere in the site, you could add a query string parameter on your redirection and check that way. Another option is to set a cookie and check for the cookie in javascript.
Here is a nice link on cookie handling in Javascript:
Javascript - Cookies
And here's one for parsing query string params/hashes in Javascript as well:
Parsing The Querystring with Javascript
Hope this points you in the right direction :)