1

First thing, keep in mind that I never used Javascript by myself (only took some script who worked at 100%) and same for the Objet Programming (learned the programmation on Pascal, 12 years ago).

Now, I have to create a little online shop on German and French.

I made the functions to set the cookies whoo keep the language selected.

But now, I wanted at least one thing : If there isn't any cookie named "Language", create one and set it to french.

How can I do that?

My function :

function setCookie(sName, sValue) {
var expDate = new Date();
expDate.setTime(expDate.getTime() + (365 * 24 * 3600 * 1000)); // ici 1 an
document.cookie = sName + "=" + escape(sValue) + ";expires=" + expDate.toGMTString() + ";path=/";
}

and the page :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <link href="./css/style.css" rel="stylesheet" media="all" type="text/css"  />
        <script type="text/Javascript" src="./javascript/cookie.js"></script>
        <title></title>
        <?php 
            require_once './includes/google_analytics.php';
        ?>
    </head>
    <body onload="setCookie('language','fr');">
    <p>
        Language : <a href="<?php echo $_SERVER['PHP_SELF']?>" onclick="setCookie('language','fr')">fr</a> /
        <a href="<?php echo $_SERVER['PHP_SELF']?>" onclick="setCookie('language','de')">de</a>
    </p>
    <?php       
        require_once './includes/menu.php';
    ?>

        <div id="contener">

        <!-- --------------------------------------------- -->    

    <?php 
        require_once './includes/header.php';
    ?>

        <!-- --------------------------------------------- --> 

        <!-- --------------------------------------------- --> 

    <?php 
        require_once './includes/footer.php';
    ?>

        </div>
    </body>
</html>

I wanted to do the test with the "onload".

Salman A
  • 229,425
  • 77
  • 398
  • 489
Anaon
  • 13
  • 2
  • 7

3 Answers3

0

This would be one way to check if the cookie is already set:

if (document.cookie.indexOf("language=") < 0)
    setCookie("language", "fr");

Note that this will also not set the cookie if any cookie has a name ending on language.


Edit:
Here is a proper function to check if a cookie with a certain name already exists.

function cookieIsset(name)
{
    var cookies = document.cookie.split(";");
    for (var i in cookies)
    {
        if (cookies[i].indexOf(name + "=") == 0)
            return true;
    }
    return false;
}

With which you could just do

if (!cookieIsset("language"))
    setCookie("language", "fr");

How to onload:
In your <head> area add the following:

<script type="text/javascript">
document.onload = function () {
    // code ...
};
</script>

PHP solution:
because OP had the tag in there originally.

if (!isset($_COOKIE['language']))
    setCookie('language', 'fr');
Cobra_Fast
  • 14,395
  • 8
  • 51
  • 97
0

I know this answer looks long but it has very handy utility methods. You can use these two utility cookies methods -

// Store the name/value pair as a cookie, encoding the value with
// encodeURIComponent() in order to escape semicolons, commas, and spaces.
// If daysToLive is a number, set the max-age attribute so that the cookie
// expires after the specified number of days. Pass 0 to delete a cookie.
function setCookie(name, value, daysToLive) {
    var cookie = name + "=" + encodeURIComponent(value);
    if (typeof daysToLive === "number")
    cookie += "; max-age=" + (daysToLive*60*60*24);
    document.cookie = cookie;
}

// Return the document's cookies as an object of name/value pairs.
// Assume that cookie values are encoded with encodeURIComponent().
function getCookies() {
    var cookies = {}; // The object we will return
    var all = document.cookie; // Get all cookies in one big string

    if (all === "") // If the property is the empty string
        return cookies; // return an empty object

    var list = all.split("; "); // Split into individual name=value pairs

    for(var i = 0; i < list.length; i++) { // For each cookie
        var cookie = list[i];
        var p = cookie.indexOf("="); // Find the first = sign
        var name = cookie.substring(0,p); // Get cookie name
        var value = cookie.substring(p+1); // Get cookie value
        value = decodeURIComponent(value); // Decode the value
        cookies[name] = value; // Store name and value in object
        }
return cookies;
}

and then -

    /* a js function to check and set cookie */
function checkAndSetCookie(sName, sdefaultValue) {
    var cookies = getCookies();
    if(typeof(cookies[sName])==="undefined"){
        setCookie(sName, sdefaultValue, 365 * 24 * 3600 * 1000)
    }
}

change html to -

<!-your html -->
<body onload="checkAndSetCookie('language','fr')">

or

<!-- add just before body -->
<script type="text/javascript">
   checkAndSetCookie('language','fr');
</script>
<body>
Moazzam Khan
  • 2,888
  • 2
  • 17
  • 32
  • The content is the three functions you wrote on your answer, nothing else – Anaon Aug 20 '13 at 13:00
  • I don't know how, but if the cookie doesn't exists, it doesn't work for me – Anaon Aug 20 '13 at 13:09
  • I use this on my menu – Anaon Aug 20 '13 at 13:13
  • May be you are using this statement inside ``, the script will set cookie only after `` is loaded. That is why its not getting reflected. I update the answer. please check if that works – Moazzam Khan Aug 20 '13 at 13:17
  • Sorry, I am not a php guy, could not make much out of it. So I am going to install php server and check it. – Moazzam Khan Aug 20 '13 at 13:26
  • I don't understand why nobody can do that, am I can't be the only one who wanted to do a website with two languages or more and one of them by default? Yes? I missed two days on that, I have to finish the website in three days... – Anaon Aug 20 '13 at 13:31
  • May be we are not able to understand your problem correctly, I am installing php server. Let me see whats real issue. meanwhile can i have the php code which generated the image you sent me? – Moazzam Khan Aug 20 '13 at 13:35
  • The only thing I want is : People come on the website for the first time, everything is in french and they have the possibility to choose German. – Anaon Aug 20 '13 at 13:42
0

The point is that you are using XHTML - and under XHTML document.cookie is a read-only property.
That means that no matter what you try, you cannot set the cookie from JavaScript. A possible way to still have the cookie set, however, is setting up an AJAX call that passes the relevant parameters to a background script. Said background script can then be used to set the cookie.

Robidu
  • 465
  • 3
  • 13