Redirect to clicked url with cookies.js - javascript

We normally use a prehome as the website of Forbes USA.
Every time we enter i.e. http://johnwho.url the page is redirected to a Welcome Home, and 8 sec later will be redirected to the original home , adding a cookie that will not show this pre-home again util 24 hores later.
like:
//Redirect
welcome = function() {
var cookie_name = 'welcome';
var value = true;
var go = Cookies.get(cookie_name);
if (go == null) {
Cookies.set(cookie_name, value, { expires: 1, path: '/' });
window.location = "/bienvenidos/"
} else {
return false;
}
}
window.onload = welcome();
But what if we want to redirect site wide, from an article or different url.
how can we change the redirect path to the selected(clicked) url??
What would be the best option to achieve this?

I know two ways: first you store all URLs which used to redirect into DB and use GET attributes which contains id from DB, another idea use GET attribute, which store URL.
For first solution URL looks like http://example.com/redirect/?urlID=100,
for the second issue -> http://example.com/redirect/?url=http://my-anothersite.example.com

Related

Allow a user access to 2 specific pages using jQuery

I have a site where users must log in to access pages. When they are not logged in I redirect them to the log in page and it then sets a cookie / token. I know this is not the most stable way of doing it but it works and its not a high traffic site whatsoever. maybe 5 users. My issue now is I need to give the users access to a contact us page even if the cookie / token is not set / valid. I tried to add another conditional to the function but it creates an infinite loop. Any ideas of handling this situation?
jQuery :
function checkIfTokenExists() {
var current_url = window.location.pathname;
var logInToken = _siteNs.Utils.readCookie('SST');
if (!logInToken) {
if (current_url != '/login.html') {
window.location.replace('/login.html');
}
} else if (logInToken) {
_siteNs.authenticateUtils.authenticateSite();
}
}
What I would like is if url is equal to /contact.html the users will be able to access regardless of cookie / token
You can early return before the token check, if the current URL is the contact page.
function checkIfTokenExists() {
var current_url = window.location.pathname;
var logInToken = _siteNs.Utils.readCookie('SST');
if (current_url == '/contact.html') {
return;
}
// ... rest of your code

A redirect is not reloading the page correctly

I am performing an update on some data, then trying to reload the current page I am on.
I have found the status code that allows me to change the redirect method from a put to a get (303). This functionality works, as when it finishes, I get the "finished loading get localhost:3000/". But the route I have predefined at "/" does not run.
The route "/" is supposed to grab some data, filter it by a boolean value, then pass it to the UI. This works when you hit the refresh button on the window. But the redirect does not work for some reason.
I have attached images for use.
This is the put route with the redirect I am having issues with.
router.put('/api/update/:id', function(req, res) {
var id = req.params.id;
Burger.update(id, function(results) {
console.log(id);
console.log(results);
})
res.redirect(303, '/');
})
Here is the "/" route that works appropriately when I hit the refresh button. but not when I use the redirected path above.
router.get('/', function(req, res) {
Burger.all(function(data) {
let eaten = [];
let notEaten = [];
// Looping through and depicting which burgers have been eaten and which ones have not.
for (var i = 0; i < data.length; i++) {
if (data[i].devoured === 0) {
notEaten.push(data[i]);
} else {
eaten.push(data[i])
}
}
// console.log(eaten);
// console.log('============');
// console.log(notEaten);
var handleBarsObject = {
eaten: eaten,
notEaten: notEaten
}
// console.log(handleBarsObject);
res.render('index', handleBarsObject);
})
})
The fact that you're doing a PUT must mean that you're doing this via an Ajax call, not something typed into the URL bar. Ajax calls by themselves do not show content in the browser. They return content to your Javascript.
If you want to follow the redirect and show the redirected page content in the browser, then you will have to examine the response from the Ajax call in your Javascript, see that it's a 3xx status code, get the Location header from the response and then set window.location to the redirected URL to cause the browser to display the redirected page.

How to add a signIn button in a website and update it based on user authentication

I am working on playframework but I believe this question is more about a general topic of web implementation. I am creating a website where I want to put my signin button on the top right corner of my home page and would like to update it based on user authentication.
i.e. if user is logged in there would be my profile and logout button and if not then there would be only signin button. I know how to implement it using different pages that uses different routes, in this case I can load complete page but I don't want to load complete page instead I would like to use popup window for signin/signup and want user to redirect back on the same page after signing in (click on signin -> signin form as a popup -> submit -> signed in) url shouldn't be changing in this process. I have seen this type of design in many popular websites but I don't know how to build one.
I did some research and found, we can do this using jquery's ajax call. With the help of ajax call we can request data from server in background (here I will request html) and update my current page DOM. In this case I am supposed to update DOM of my navbar's top right corner so I will request html for that part only but I don't know exactly how to do it? I am new to website designing, would it be a good design or there is other best way to do the same task?
It would be also appreciable if anyone can tell me how should I update link to my related css & js file page by page. I mean if some css file is not being used in a particular page how to remove reference to that and add a new one relevant to that page.
Sorry, If it looks fool of asking such basic questions here but I just want to clear my concept in web-designing and implementation. It would also be helpful if anyone can suggest me a book or link to read about these topics.
If I understood your question correctly, you were asking for help with the DOM -part of the equation?
Here's an example (see the JSFiddle, for the whole thing, as the current code expects the login button to be present at launch):
function login (logtype) {
var insertInput = function (value) {
document.getElementById('logincontainer').insertBefore(
document.createElement('input'),
document.getElementsByTagName('input')[0]);
var newButton = document.getElementsByTagName('input')[0];
newButton.type = 'button';
newButton.value = value;
if (value === 'logout') {
newButton.onclick = function () {login('logout');};
}
if (value === 'login') {
newButton.onclick = function () {login('login');};
}
if (value === 'myprofile') {
newButton.onclick = function () {window.location.href='http://jsfiddle.net/user/b00t/fiddles/';};
}
},
deleteInput = function () {
document.getElementById('logincontainer').removeChild(document.getElementById('logincontainer').lastChild);
};
if (logtype === 'login') {
var logIn = confirm('Login?');
if (logIn) {
insertInput('myprofile');
insertInput('logout');
deleteInput();
}
}
else if (logtype === 'logout') {
var logOut = confirm('Logout?');
if (logOut) {
insertInput('login');
deleteInput();
deleteInput();
}
}
}
JSFiddle

Remove query string in url when user reloads page

Hi I have am logging in users and redirecting them to http://domain.com/profile/#welcomemessage or http://domain.com/profile/?msg=showwelcomemessage
So basically it shows welcome message based on query string.When Users reload the page I want to remove the query.i.e..basically I want to show the welcome message only once.
If this is not possible.Should I use localstorage ? will this work on all browsers?
You are probably looking for
window.history.replaceState
Usage:
window.history.replaceState( {} , 'foo', '/foo' );
From w3.org:
history . replaceState(data, title [, url ] )
Updates the current entry in the session history to have the given
data, title, and, if provided and not null, URL.
or you can use localStorage like this:
if (!localStorage.getItem("visited")) {
//yourmessage
localStorage.setItem("visited", "true");
}
//clear the localStorage when the tab is closed
window.onbeforeunload = function() {
localStorage.removeItem("visited");
};
localStorage sounds like the way to go. Or a session if you are more server-orientated. localStorage does work in ie8 and above
For localStorage:
if (!localStorage.hideWelcomeMessage) {
document.getElementById('welcome-message').style.display="block";
localStorage.hideWelcomeMessage = true;
}
and html:
<div id="welcome-message" style="display:none;">Welcome!</div>
The above assumes the id is "welcome-message" but of course you can change that up.

how to force redirect to login page in javascript

I am building a website where I want users to have to log in to be able to view a certin page (kn this case it is called gallery.php) I implemented some code I found on this site, which redirects the user back to the login page when they click on the gallery link in the menu. However when I log in, and get redirected to the gallery again, the website does not acknowledge that I have logged in and redirects me back to the login page again. I am aware that questions like this have been asked before, but any help would be appreciated. My code is bellow
//from login.html
<!--//
/*This Script allows people to enter by using a form that asks for a
UserID and Password*/
function pasuser(form) {
if (form.id.value=="Admin") {
if (form.pass.value=="rycbar123") {
var sessionTimeout = 1; //hours
var loginDuration = new Date();
loginDuration.setTime(loginDuration.getTime()+(sessionTimeout*60*60*1000));
document.cookie = "SistaDansenSession=Valid; "+loginDuration.toGMTString()+"; path=gallery.php";
location="gallery.php"
} else {
alert("Invalid Password")
}
} else { alert("Invalid UserID")
}
}
//from gallery.php
<!--force login code-->
<script type="text/javascript">
if (document.cookie.indexOf("SistaDansenSession=Valid") == -1) {
alert("You must be logged in to view this page")
location.href = "login.html";
}
else {
alert("login succesful")
} </script>
Thanks so much
Try changing:
if (document.cookie.indexOf("SistaDansenSession=Valid") == -1)
to
if (document.cookie.indexOf("SistaDansenSession") < 0)
When you set the cookie, you are setting the cookie attribute 'SistaDansenSession' equal to the value 'Valid'. In your original code, you are attempting to retrieve a cookie attribute 'SistaDansenSession=Valid', whereas the attribute you want to retrieve is just 'SistaDansenSession'. When the cookie is set, the attribute exists, so it will have an index that is >= 0. In that case, the redirect to the login does not occur - which I think is your desired behavior.

Categories