Search code examples
phpjavascriptformscookiessetcookie

Store Form Values In Cookie


I've been trying to teach myself about cookies for the last couple of hours and how I would go about storing values from a few form fields into a cookie.

Im not having much luck, all the examples I've found havent been very helpful. Should I generate them using PHP or JS? Any feedback or a kick in the right direction would be highly appreciated!

http://jsfiddle.net/yucM7/

Thanks in advance!


Solution

  • Here's an example.

    All you need is jQuery and cookie plugin

    Keep in mind, there're couple of changes in html code.

    $(document).on('submit', '#myForm', function() {
       // serialize our form (get string containing field names and values)
       dataString = $(this).serialize();
       // set new cookie
       $.cookie('formCookie', dataString);
       return false;
    });
    
    $(document).on('click', '#getCookie', function() {
       // get serialized string from cookie    
       cookieData = $.cookie('formCookie');
       // if cookie exists continue
       if (cookieData != null) {
            // split cookieData string into an array of fields and their values
            cookieArray = cookieData.split('&');
            // go through each field and split it too to get field name and it's value
            $.each(cookieArray, function(k, v) {
              field = v.split('=');
              // populate field with data
              $('#myForm [name="'+field[0]+'"]').val(field[1]);
            });
        }
       return false;
    });