Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between .serialize() and .serializeArray()?

I'm experimenting with sending a form to a controller. jQuery documentation says that .serializeArray() should send a json array, and .serialize() should create a query string.

However, when I try it, and inspecting with IE9 F12-mode, it looks like a query string, in both cases. Which ever call I make...

What am I missing?

like image 383
kaze Avatar asked May 03 '12 11:05

kaze


People also ask

What does serialize method do?

The serialize() method creates a URL encoded text string by serializing form values. You can select one or more form elements (like input and/or text area), or the form element itself. The serialized values can be used in the URL query string when making an AJAX request.

What is data $( this serialize ()?

Data serialization is the process of converting an object into a stream of bytes to more easily save or transmit it. The reverse process—constructing a data structure or object from a series of bytes—is deserialization.

What is the use of serialize in JavaScript?

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() .


1 Answers

serializeArray creates an array (not a "json array" -- there is no such thing); you can test this yourself with console.log($("#myform").serializeArray()). On the other hand, serialize creates a query string that's meant to be part of an HTTP request. Both representations are equivalent in the sense that using appropriate code you can convert one to the other without any ambiguity.

The reason for both versions being available is that serialize is more convenient when you just want to make an HTTP request (just put the result in the query string) while serializeArray is more convenient if you want to process the results yourself.

jQuery's AJAX methods don't care if you give them one or the other because they detect the type of the parameter and convert it to a query string if it's not one already, so by the point the request is made outside observers cannot tell what was the original format of the parameters.

like image 152
Jon Avatar answered Sep 25 '22 13:09

Jon