jQuery AJAX Form Submit Example

In jQuery AJAX Form Submit Example, I have explained how to submit a HTML Form asynchronously using jQuery AJAX API.

Topics Covered:
1).Submit a Simple HTML Form
2).Submit Multipart/form-data Form

1).Submit a Simple HTML Form

Below is the Simple HTML Form.

<form name="ajaxform" id="ajaxform" action="ajax-form-submit.php" method="POST">
	First Name: <input type="text" name="fname" value =""/> <br/>
	Last Name: <input type="text" name="lname" value ="" /> <br/>
	Email : <input type="text" name="email" value=""/> <br/>
</form>

For jQuery Ajax Form Submit, we can use jQuery.ajax()  or jQuery.post() method. To serialize form data, we can use jQuery.serialize() or jQuery.serializeArray().

//callback handler for form submit
$("#ajaxform").submit(function(e)
{
	var postData = $(this).serializeArray();
	var formURL = $(this).attr("action");
	$.ajax(
	{
		url : formURL,
		type: "POST",
		data : postData,
		success:function(data, textStatus, jqXHR) 
		{
			//data: return data from server
		},
		error: function(jqXHR, textStatus, errorThrown) 
		{
			//if fails		
		}
	});
    e.preventDefault();	//STOP default action
    e.unbind(); //unbind. to stop multiple form submit.
});

$("#ajaxform").submit(); //Submit  the FORM

jQuery AJAX Form Submit Example

2).Submit Multipart/form-data Form

Submitting a simple HTML form with jQuery is very easy, but submitting a HTML Form with File uploads is not straightforward. In jQuery, there is no direct API to send files. So we can use HTML5 FormData API to read the Form data and use $.ajax() API to submit the data.

HTML Form provides two types of encoding.
a).application/x-www-form-urlencoded
This is form Simple HTML forms.
b).multipart/form-data
This allows files to be send through POST method.

Below is the HTML form with enctype=”multipart/form-data” which supports file uploads.

<form name="multiform" id="multiform" action="multi-form-submit.php" method="POST" enctype="multipart/form-data">
	Name: <input type="text" name="name"  value="Ravi"/> <br/>
	Age :<input type="text" name="age"  value="1" /> <br/>
	Image :<input type="file" name="photo" /><br/>
</form>

 

Below code uploads the Files & Data without refreshing the page:

//Callback handler for form submit event
$("#multiform").submit(function(e)
{

	var formObj = $(this);
	var formURL = formObj.attr("action");
	var formData = new FormData(this);
	$.ajax({
     	url: formURL,
	type: 'POST',
        data:  formData,
	mimeType:"multipart/form-data",
	contentType: false,
        cache: false,
     	processData:false,
	success: function(data, textStatus, jqXHR)
	{

	},
	 error: function(jqXHR, textStatus, errorThrown) 
	 {
	 } 	        
	});
    e.preventDefault(); //Prevent Default action. 
    e.unbind();
}); 
$("#multiform").submit(); //Submit the form

 

Above code works fine in all the HTML5 browsers, but it doesn’t work in old browsers.
To support Old browsers, we can use hidden iframe technique where form target is set to hidden iframe.

$("#multiform").submit(function(e)
{
	var formObj = $(this);
	var formURL = formObj.attr("action");

	//generate a random id
	var  iframeId = 'unique' + (new Date().getTime());

	//create an empty iframe
	var iframe = $('<iframe src="javascript:false;" name="'+iframeId+'" />');

	//hide it
	iframe.hide();

	//set form target to iframe
	formObj.attr('target',iframeId);

	//Add iframe to body
	iframe.appendTo('body');
	iframe.load(function(e)
	{
		var doc = getDoc(iframe[0]); //get iframe Document
		var docRoot = doc.body ? doc.body : doc.documentElement;
		var data = docRoot.innerHTML;

		//data is returned from server.
	});

}); 
$("#multiform").submit();

 

To Support all browsers, Putting all together.

function getDoc(frame) {
     var doc = null;

     // IE8 cascading access check
     try {
         if (frame.contentWindow) {
             doc = frame.contentWindow.document;
         }
     } catch(err) {
     }

     if (doc) { // successful getting content
         return doc;
     }

     try { // simply checking may throw in ie8 under ssl or mismatched protocol
         doc = frame.contentDocument ? frame.contentDocument : frame.document;
     } catch(err) {
         // last attempt
         doc = frame.document;
     }
     return doc;
 }
$("#multiform").submit(function(e)
{

	var formObj = $(this);
	var formURL = formObj.attr("action");

	if(window.FormData !== undefined)  // for HTML5 browsers
	{

		var formData = new FormData(this);
		$.ajax({
        	url: formURL,
	        type: 'POST',
			data:  formData,
			mimeType:"multipart/form-data",
			contentType: false,
    	    cache: false,
        	processData:false,
			success: function(data, textStatus, jqXHR)
		    {

		    },
		  	error: function(jqXHR, textStatus, errorThrown) 
	    	{

	    	} 	        
	   });
        e.preventDefault();
        e.unbind();
   }
   else  //for olden browsers
	{
		//generate a random id
		var  iframeId = 'unique' + (new Date().getTime());

		//create an empty iframe
		var iframe = $('<iframe src="javascript:false;" name="'+iframeId+'" />');

		//hide it
		iframe.hide();

		//set form target to iframe
		formObj.attr('target',iframeId);

		//Add iframe to body
		iframe.appendTo('body');
		iframe.load(function(e)
		{
			var doc = getDoc(iframe[0]);
			var docRoot = doc.body ? doc.body : doc.documentElement;
			var data = docRoot.innerHTML;
			//data is returned from server.

		});

	}     
});
$("#multiform").submit();

jQuery AJAX Multipart Form Submit ExampleDownload

Same functionality you can get by using Ajax Form plugin.


I am a Developer. My motto: "Language is not a barrier"

All posts by Ravishanker Kusuma