3

Is there any way to store form state in for example cookie and retrieval it ?
I checked serialize API but I have no idea how to retrieval serialized data on the form.
Is it possible?

Update

I putted my code here. Check the javascript code after // End of cookie plugin becasue I am sure that jQuery plugin works right.

Shahin
  • 12,543
  • 39
  • 127
  • 205
  • there is a plugin called [dumbFormState](http://www.jasonsebring.com/dumbFormState). try it out – Sufendy Jul 04 '11 at 03:50

3 Answers3

3

Yes, you can serialize form values with serialize(). Syntax:

$("#your_form").serialize()

will return a string you can handle, or save to cookie (you can use the jquery cookie plugin).

EDIT: The above code will serialize, but will be hard to retrieve.
You should better use serializeArray(), which returns an array of name value pairs ( like: [{name: "age", value: "23"}, {name: "sex", value: "male"}]). You can see the docs for better explanation.

With that, we can build a "form to string" function and a "string back to form" function:

function form2string($form) {
  return JSON.stringify($form.serializeArray());
}

function string2form($form, serializedStr) {
  var fields = JSON.parse(serializedStr);
  for(var i = 0; i < fields.length; i++){
    var controlName = fields[i].name;
    var controlValue = fields[i].value;
    $form.find('[name=' + controlName + ']').val(controlValue);
  }
}

Use form2string to serialize it and string2form to set the string back to the form. To store and retrive the serialization, you can use the cookie plugin.

Hope this helps. Cheers

PS: JSON methods will work only in modern browsers

VCD
  • 889
  • 10
  • 27
Edgar Villegas Alvarado
  • 18,204
  • 2
  • 42
  • 61
  • Villegas Alvarado As I said I know serialize API but I have no Idea how to retrieval serialized data on the form. – Shahin Jul 04 '11 at 03:48
  • Villegas Alvarado Thank you so much for your attention. I used your code but I don't know why it doesn't work... I putted my code here http://jsfiddle.net/BwUM4/1/ I am sure that jQuery plugin works right. would you please check my code or create sample example on Jsfiddle ? – Shahin Jul 04 '11 at 04:43
  • Check the javascript code after // End of cookie plugin becasue I am sure that jQuery plugin works right. – Shahin Jul 04 '11 at 04:46
  • 1
    I changed some parts in your jsfiddle and It's running OK now. Some considerations: `.serializeArray()` can be applied only to `
    ` elements, so I replaced your `
    ` by a ``. Also, serialization needs that elements have a name, which I also added to the elements. Now it runs fine!
    – Edgar Villegas Alvarado Jul 04 '11 at 05:08
  • @Thank you so much :) So can't we use serializeArray with Div ? – Shahin Jul 04 '11 at 05:25
0

I prefer .serialize() and parsing with .split() over .searializeArray() and JSON parsing.

qs = $("#form_id").searialize()  // generates query string, e.g: "name=John&age=21"
f = {}
qs.split("&").map( p => p.split("=") ).forEach( ([k,v]) => f[k] = v )
// f === {name: "John", age: "21"}
Zaz
  • 46,476
  • 14
  • 84
  • 101
0

Inspired by Edgar's answer but the copy-paste version.

var form = $('form');
if (form.length) {
    var form_data = readCookie('saved_form');
    if (form_data != null) {
        string2form(form, form_data);
    }

    form.submit(function() {
        var form_data = form2string(form);
        createCookie('saved_form', form_data, 5);
    });
}

function createCookie(name, value, days) {
    var expires;

    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    } else {
        expires = "";
    }
    document.cookie = encodeURIComponent(name) + "=" + encodeURIComponent(value) + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = encodeURIComponent(name) + "=";
    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)
            return decodeURIComponent(c.substring(nameEQ.length, c.length));
    }
    return null;
}


function form2string($form) {
  return JSON.stringify($form.serializeArray());
}

function string2form($form, serializedStr) {
  var fields = JSON.parse(serializedStr);
  for(var i = 0; i < fields.length; i++){
    var controlName = fields[i].name;
    var controlValue = fields[i].value;
    if (controlValue != '' && $form.find('[name=' + controlName + ']').val() == ''){
        $form.find('[name=' + controlName + ']').val(controlValue);
    }
  }
}
Mark
  • 373
  • 2
  • 11