Sunday 8 September 2013

Encode form elements for ajax submit

Hi friends,
Today my description is about submit form elements through ajax.Submit form through javascript can done using submit() method .
But when  try to submit a form through ajax we need to provide the name of elements and its value as data parameter in jquery $.ajax();

We can done this like
var data='';
data+='name='+$('#name').val()+'&age='+$('#age').val();


But we can use jquery serialize() method we can do this all stuff in single step,like this:
var data=$('#frm').serialize();


Example:

<form id="frm">
<input type="text" name="name"/>
<input type="text" name="age"/>
<input type="button" onclick="submitFrm();"/>
</form>

<script type="text/javascript">
function submitFrm()
{
var data=$('#frm').serialize();
$.ajax({
url:'action.php',
data:data,
type:'post',
datatype:'html',
success:function(){
alert('success...');
},
error:function(){
alert('error...');
}
});
}
</script>


That is we can use serialize() to easy ajax form submit.
If we want to add some additional parameters  existing outside of the form,
add them easily by using '&' like this.
var data=$('#frm').serialize();
data+='&teacher_name='+$('#teach_name').val();

Thank you.

Search This Blog