Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery serialize an object?

Say I have something like:

var obj = {id: 1, name: "Some name", color: "#444444" };

I want to serialize that object. I tried:

$(obj).serialize();

but that didn't work.

Any ideas?

like image 513
Seamus James Avatar asked Feb 13 '12 19:02

Seamus James


People also ask

What is serialization and deserialization in jQuery?

The serialize() method is an inbuilt method in jQuery which is used to create a text string in standard URL-encoded notation. This method can act on a jQuery object that has selected individual form controls, such as input, textarea etc. Syntax: $(selector).serialize()

How do I fetch a single value from serialize ()?

To get value from serialized array, use th serializeArray( ) method. The serializeArray( ) method serializes all forms and form elements like the . serialize() method but returns a JSON data structure for you to work with.

What is JavaScript serialize?

The process whereby an object or data structure is translated into a format suitable for transfer over a network, or storage (e.g. in an array buffer or file format). In JavaScript, for example, you can serialize an object to a JSON string by calling the function JSON. stringify() .

What is serialized form?

In computing, serialization (US and Oxford spelling) or serialisation (UK spelling) is the process of translating a data structure or object state into a format that can be stored (for example, in a file or memory data buffer) or transmitted (for example, over a computer network) and reconstructed later (possibly in a ...


3 Answers

You should use jQuery.param() instead.

Working Example

With vanilla JS, you would use JSON.stringify instead.

like image 124
Sarfraz Avatar answered Nov 02 '22 07:11

Sarfraz


As mentioned you should use .param()

$.param({id: 1, name: "Some name", color: '#444444' })

But also you need to be careful with your syntax. Your brackets don't match, and that color will need quotation marks. jsFiddle

like image 43
Sinetheta Avatar answered Nov 02 '22 07:11

Sinetheta


You could use JSON.stringify to serialize your object, and you'd have to wrap your color string correctly:

var obj = {id: 1, name: "Some name", color: '#444444' };
var serialized = JSON.stringify(obj);
// => "{"id":1,"name":"Some name","color":"#444444"}"
like image 26
Tharabas Avatar answered Nov 02 '22 07:11

Tharabas