Robert Mailloux
Robert Mailloux

Reputation: 397

WHEN to use serialize vs just regular POST

I recently asked a question that was partially answered but I was hoping someone could explain this a little clearer. Its regarding PHP and the serialize function.

So I have a form with 12 fields, all with names. Traditionally I would just use the POST method, send them to a PHP page and then supply them into a database.

Today I stumbled upon the serialize method but after using it, it seems like it doesnt do anything that a regular POST statement would do. For example, if I wanted to use serialize, I would do the following:

var formData = $('#contForm').serialize();
$.post('functs.php',formData,dispAdd);

Then to print a value I would use

echo $_POST['value_name']

What I see happening is that with or without the serialize, I get the same results. Am I missing something here?

Upvotes: 9

Views: 137

Answers (1)

Techie
Techie

Reputation: 45124

The .serialize() method creates a text string in standard URL-encoded notation. It operates on a jQuery object representing a set of form elements. The form elements can be of several types. Read more.

.serialize() is used when you are sending data through an AJAX request. It's the same as submitting a form using a submit button. Only difference it when you use AJAX it does not refresh the page. That's why you get the same results even though you submit the form using a submit button or .serialize() when using AJAX.

.serializeArray() would be an alternative to .serialize().

Remember if you don't use .serialize() you have to create your key-value pairs manually as @Akam mentioned in the comment above.

And finally

When to use serialize <-- When you use AJAX to post data

When regular POST <-- When you use submit button to post data

Upvotes: 4

Related Questions