2

I'm working on a project in which the user is sent to the directory name they entered in an input, like so:

function sendanswer(e) {
if (e.keyCode === 13) {
    e.preventDefault();
    var answer = document.answerarea.input.value;
    if (answer) {window.location.href = answer;}
}
}

document.answerarea.input.onkeypress = sendanswer;

This works fine. But now I want for the user to be automatically redirected to the directory they specified every time they visit the page, BUT only if they didn't recieve a 404 error after navigating to the directory. I imagine this would be accomplished by erasing the cookie when the 404 page is visited.

But how would the redirecting-to-cookie process work?

deanboysupreme
  • 77
  • 2
  • 12

1 Answers1

2

When you get input from use set a cookie using this code:

function sendanswer(e) {
  if (e.keyCode === 13) {
      e.preventDefault();
      var answer = document.answerarea.input.value;
      if (answer) {
         window.location.href = answer;
         //SET COOKIE WITH NAME redirectPath
         document.cookie="redirectPath="+ answer;
      }
  }
}

Now on your home page (the page which user gets on visiting your site) add following call on-page load:

window.onload=function(){
    var kuki = "redirectPath=";//NAME OF COOKIE WE SET
    var cookies = document.cookie.split(';');
    for(var i=0;i < cookies.length;i++) {
        var c = cookies[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(kuki) == 0){
           var path = c.substring(kuki.length,c.length);
           //MOVE USER TO STORED PATH
           document.location.href=path;
        }
    }   

}

A better approach will be to read cookie on server-side and redirect user to their favourite folder from there.

For more reference check this answer.

Community
  • 1
  • 1
TheVillageIdiot
  • 40,053
  • 20
  • 133
  • 188
  • Thank you! After some testing this doesn't seem to be working, but I'm running on localhost. I'm seeing if this works if i put it online. – deanboysupreme Jul 06 '15 at 00:29
  • What error you are getting? Have you checked dev-console/firebug and tried to step through the code setting/reading cookie? – TheVillageIdiot Jul 06 '15 at 00:32
  • I'm not getting any errors, but it doesn't look like the page has set any cookies. – deanboysupreme Jul 06 '15 at 00:43
  • this almost works! the cookie is set but the redirect is not working. i get the error `ncaught ReferenceError: nameEQ is not definedwindow.onload @ main.js:21` – deanboysupreme Jul 06 '15 at 01:25
  • fixed!!! sorry got code from quirks-mode page and forgot to fix it all. But please do read the other SO answer linked and read something on JS. This was simple and easily fixable. Hope didn't waste your day. – TheVillageIdiot Jul 06 '15 at 04:24