Thursday, November 10, 2011

Save and Restore Form Cookies using JavaScript


I was developing  a retailer web application and working on  Product Comparison functionality.There was a requirement where I want to persist info (product Id from different category page) across multiple pages using javascript. Then use those product ids in Product Comparison page.Each Product Category page lists muliple products,  with a check box associated with each product, which  allow user  to select products to compare. As per requirement user can select products from diferent category and when click compare product button ,then all selected products from diferent page must be go to compare Product page.So I need to persist Product id in cookie .

1) Here to impliment this functionality I have used one Hidden input control to get data from cookie on load event.

<input type="hidden" id="HiddenVar" runat="server" enableviewstate="true" />

2) Then the question is when to save data in Cookie.To save product Id into cokkie I have written  a javascript function and call it on onClick event of CheckBox.

checkbox.Attributes.Add("onClick""updateProductIdInArray(this)");

Here I have used a global variable as  array to update selected Product ids .As a result whenever a uer check or uncheck the check box control, the array object will be updated (add or remove product id from array object). Then update the value of hidden control by getting all ids from array object (you can write  a separate function to get all product id from array  and make a text separated by comma ).

3) Write a function to save the info in a cookie and call the function when user click on  button or link to go to different page.The idea is before go to the specified page the javascript function will save the data from Hidden input control value in to a cookie.

Control.Attribute.Add("onclick""javascript:SaveSelectedProductId(););
      //Save Product Ids in Session
      function SaveSelectedProductId(url) {
        //Get Hidden Control value
        var HiddenControl = document.getElementById('<%= HiddenVar.ClientID %>');
        var dataTosav = HiddenControl.value;
        createACookie(cokkieName, dataTosav, '1');
    }
  //Create Cokkie
      function createACookie(name, value, days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            var expires = "; expires=" + date.toGMTString();
        }
        else
            var expires = "";
        document.cookie = name + "=" + value + expires + "; path=/";
     }

4) Now the time to read the values from cokkie and delete  the cokkie you need to do it  on Load event  of the page or any Control.For that you need to use a Hidden control which will get the value from cookie and also be available to javascript so that the value can be resuse.

//Read value from Cokkie
    function ReadCookie() {
        var HiddenctrlOnLoad = document.getElementById('<%= HiddenVar.ClientID %>');
        var nameEQ = cokkieName + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0) {
                HiddenctrlOnLoad.value = c.substring(nameEQ.length, c.length);
                EraseCookie(cokkieName);
            }
         }
     }
    //Erage Cokkie
    function EraseCookie(name) {
        createCookie(name, "", -1);
    }

Here the cookie must be enabled in browser to support this functionality .