Variable Scope and Cookie Issue
Posted: Mon Mar 16, 2009 8:23 pm
I have a function that executes when I send a request to the server. Inside the function, I grab the value of a cookie and then pass that value to the server by attaching it to the URL in the request. Unfortunately, I cannot successfully get the value of the cookie into the cookieValue variable. The first group of statements below (in red) contain the correct cookie value in the variable cookeValue; general. But, if I comment that line out and use the second group of red lines, the variable cookieValue has the following incorrect value; PHPSESSID=ad2307d8491584317b165ba0907a894f .
I am fairly new to using javascript and cookies, but from what I can see I have made the cookieValue variable global to the function, so I am completely confused on why this is happening.
Thanks in advance for any time spent and help - Adam
I am fairly new to using javascript and cookies, but from what I can see I have made the cookieValue variable global to the function, so I am completely confused on why this is happening.
Thanks in advance for any time spent and help - Adam
Code: Select all
function sendRequest(){
var cookie_name = "quick_view";
var cookieValue;
var namestart;
var nameend;
var index;
if(document.cookie)
{
index = document.cookie.indexOf(cookie_name);
if (index != -1)
{
namestart = (document.cookie.indexOf("=", cookie_name) + 1);
nameend = document.cookie.indexOf(";", cookie_name);
if (nameend == -1) {nameend = document.cookie.length;}
[color=#FF0000] cookieValue = document.cookie.substring(namestart, nameend);
//document.write(cookieValue);[/color]
}
}
[color=#FF0000] //cookieValue = document.cookie.substring(namestart, nameend);
//document.write(cookieValue);[/color]
var mytime= "ms=" + new Date().getTime(); // use time to prevent IE from caching page
var toggle= "&toggle=" + cookieValue;
var url = "refreshHeader.php?" + escape(mytime) + escape(toggle);
ajaxRequest.open("GET",url,true);
ajaxRequest.onreadystatechange = updatePage;
ajaxRequest.send(null);
}