Simple case of overcooking
$(function() {
if ($.cookie('mem')) window.location.href = 'http://www.mysite.com/home-en.php';
});
Question
I'm quite new to jQuery, and I'm trying to get the jQuery plugin, jquery.cookie.js to write a cookie, and then redirect based on the cookie value. Here's an outline of what I'm trying to accomplish:
Upon landing on a splash page, the user selects their language preference. They can also check a "remember me" checkbox, which writes the cookie lang-pref
with a value of either en
or fr
. Upon future visits, visitors are redirected to either an English homepage or a French homepage.
Here's my code for writing the cookie:
$(function()
{
$("#en").change(function() //#en is the id of the checkbox
{
if ($(this).is(":checked"))
$.cookie('mem', 'en', { expires: 3652 }); // mem is the cookie name, en is the value
})
});
And here is the code to read the cookie, which I'm reasonably sure I've screwed up, as the redirect doesn't work. I'm not sure how to fix it, though:
$(function() {
if ($.cookie('mem'))
$(location).html ("window.location.href = 'http://www.mysite.com/home-en.php'");
});
I've looked over the docs for this plugin, but I'm still not sure how to use the actual cookie's value to perform actions: the examples given on the project's GitHub page, for example, shows how to read a cookie, simply by doing what I've done in the code above.
Long story short, I can't figure out how to read the value of a cookie, and then use said value to perform a redirect.
Solution
Simple case of overcooking
$(function() {
if ($.cookie('mem')) window.location.href = 'http://www.mysite.com/home-en.php';
});
OTHER TIPS
The cookie's value is returned by $.cookie('mem')
. To account for both English and French redirections (or any future language value) you can do the following:
$(document).ready(
function() {
var language_preference = $.cookie('mem');
if (language_preference) {
window.location.href = 'http://www.mysite.com/home-'+language_preference+'.php';
}
}
);
However, note this kind of language detection and redirection is usually done on the server-side. In PHP, after the cookie was set, it could be accessed in the global variable $_COOKIE
. See documentation in the PHP Manual.
For example, instead of doing the redirection in the JS of another page, you can do this on the server-side with PHP:
if ($_COOKIE['mem']) :
header('Location: http://www.mysite.com/home-'.$_COOKIE['mem'].'.php');
exit;
endif;
The main advantage of this approach is that the user goes through only one splash page to get to the homepage, instead of two.