Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store other languages (unicode) in cookies and get it back again

Can anyone help me understand how to store a cookie value that is in another language and than how to retrieve it again in that language.

I seem to have my foreign language cookies turn to garbage when retrieved after being stored.

Some code:

Write cookie code:

   function writecook() {
            document.cookie = "lboxcook=" + document.getElementsByTagName('input')[0].value;
            //input[0] is the input box who's value is stored
   }

Retrieve Cookie code:

  <script language="JavaScript"> 
            function get_cookie ( cookie_name )
            {
               var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );


               if ( results )
               return ( unescape ( results[2] ) );
               else
               return null;
            }
            </script> 

Thanks.

like image 476
Zigglzworth Avatar asked Feb 04 '11 18:02

Zigglzworth


People also ask

How do I restore my cookie value?

If you want to find the value of one specified cookie, you must write a JavaScript function that searches for the cookie value in the cookie string.

How do you overwrite cookies?

To update a cookie, simply overwrite its value in the cookie object. You do this by setting a new cookie on the document with the same Name, but a different Value.

Which is the correct syntax for expire a cookie?

SOLUTION. document. cookie = 'key1 = value1; key2 = value2; expires = date'; is the correct syntax to create a cookie using JavaScript.


1 Answers

Use encodeURIComponent() when setting the cookie and decodeURIComponent() when retrieving it.

var cookieValue = document.getElementsByTagName('input')[0].value;
document.cookie = "lboxcook=" + encodeURIComponent(cookieValue);

function get_cookie(cookie_name) {
    var results = document.cookie.match ('(^|;) ?' + cookie_name + '=([^;]*)(;|$)');
    return results ? decodeURIComponent(results[2]) : null;
}
like image 73
Tim Down Avatar answered Oct 27 '22 22:10

Tim Down