Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery serialize and unserialize

Tags:

jquery

I want to serialize and un-serialize a form with jQuery.

How can I get all attributes of all elements in a serialized way?

like image 749
James Avatar asked Jun 23 '10 09:06

James


2 Answers

.serialize() will map your input controls that have a name attribute defined into a standard query string:

foo=bar&bar=foo&and=soon

That kind of string is easy accesible in almost every "backend" programming language.

If you need to serialize object information, use JSON.

var obj = {
    foo:  'bar',
    more: 'etc
};

serialize this with window.JSON.stringify(obj);. To unserialize such a JSON string, use window.JSON.parse(str);, which returns a javascript object.

Many languages support this principle.

like image 148
jAndy Avatar answered Oct 02 '22 05:10

jAndy


2020 solution

serialize()

Is included in jQuery itself for this very purpose https://api.jquery.com/serialize/

$('#someKind .ofASelectorForYour form').serialize(); (returns serialized string)

unserialize()

Is not included in jQuery, but, the documentation says

The .serialize() method creates a text string in standard URL-encoded notation.

...so, in 2020, we can leverage the URLSearchParams interface:
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
https://url.spec.whatwg.org/#interface-urlsearchparams

function unserialize(serializedData) {
    let urlParams = new URLSearchParams(serializedData); // get interface / iterator
    let unserializedData = {}; // prepare result object
    for (let [key, value] of urlParams) { // get pair > extract it to key/value
        unserializedData[key] = value;
    }

    return unserializedData;
}

(returns object of unserialized key => value pairs)
A one-liner for one-time usage extractor (your data in sData, result in unsData):

let prms = new URLSearchParams(sData); let unsData = {}; for (let [k, v] of prms) unsData[k] = v;

BTW: as MDN docs say,

following two lines are equivalent:
for (const [key, value] of mySearchParams) {}
for (const [key, value] of mySearchParams.entries()) {}

like image 30
jave.web Avatar answered Oct 02 '22 06:10

jave.web