Posting a File with AJAX

In order to POST a file in a regular form, you will find that you need to change the enctype from the default of application/x-www-form-urlencoded to:

<form action="myurl" method="POST" enctype="multipart/form-data">
 

Similarly, by default, an AJAX request will use the default urlencoded form enctype. In order for the file to be uploaded, we need to change the enctype. To do this, we need to stop jQuery from processing the data prior to sending. The following ajax call does this:

	//http://api.jquery.com/jQuery.ajax/
	$.ajax({
	    url: targetUrl,
		type: method,
		data: data,
		async: true,
		cache: false,
		processData: false,  // tell jQuery not to process the data
		contentType: false,   // tell jQuery not to set contentType
		beforeSend: function (jqXHR, settings) {
			//returning false will abort the request
			//http://api.jquery.com/jQuery.ajax/#jqXHR - jqXHR info
		},
		success: function (data, status, xhr) {
			//perform action here
		},
		error: function (xhr, status, error) {
			//perform action here
		},
		complete: function (jqXHR, textStatus) { 
             //perform action here
        }
	});

So how do we present the data? Javascript has a FormData object we can use:

    var data = new FormData(document.getElementById('#myformID'));

This is then used in the ajax request as the source of the "data" option. It will contain all input fields found within the target form.



Tagged: AJAX, JQuery,
Categorised: JQuery,
By:
On: