using jQuery serialize to handle posting field

Iwas doing some ajax form submission today with jQuery and just find out this new technique that handle all the posting field. Let’s take a look the jQuery Post syntax

jQuery.post( url, [ data ], [ success(data, textStatus, XMLHttpRequest) ], [ dataType ] )

as you can see the second parameter is [data] which mean that all the data that you need to pass to your submit form. What i use to do is getting variable from each field and form up a nicely JSON data array like this, which is a very time-consuming way.

{ name: "Knight", Email: "knight@email.com", Age: "30" }

the new way that i just find out today ( late better than never ) is to make use of the serialize function. I created a sample form with the code below.

[html]
<form id="<span class=">regoform</form>" action="submit.php" methd="post">
<fieldset>
<legend>Register Form</legend>
Name <input type="text" name="name" />

Email <input type="text" name="email" />

Age <input type="text" name="age" />

<button id="regobutton">register</button>
</fieldset>
</form>
[/html]

as you can see this is a normal form with 3 text field, by using the jQuery serialize function , I m grabbing all the data from each field and assign the value with the  name variable, example email variable will have the email value that I key in.It is quick and simple solution to handle these posting field.

[javascript]
<script type="text/javascript">
$(document).ready(function() {
$("#regobutton").click(function(){
$.post("submit.php", $("#regoform").serialize());
});
});
</script>
[/javascript]

a few thing to take note when writing the jQuery Post ,  every single field need to be within the form elements, so that every field value will be pick up by the serialize function. Another important thing will be the registration button, you need to make sure it will respond when user click on it.

You may also like...