Due to security issue, it is forbidden to post a file( multipart/form-data ) using Javascript XMLHttpRequest object, so it has been impossible to post a file directly to your backend using Ajax. However there is a workaround to get file posting possible similiar to ajax. In this tutorial, we will teach how to use JQuery to post a file using iframe. To simplify the process, we will use JQuery to handle javascript part. The final task can be verified using Firebug, you will be able to see file field being posted from Firebug.
<html>
<head>
<script type="text/javascript" src="js/jquery-1.4.2.min.js">
</script>
</head>
<body>
</body>
</html>
Create a form inside "test.html" for testing:
<FORM METHOD=POST ENCTYPE="multipart/form-data" ACTION="upload.php">
File: <INPUT TYPE=FILE NAME="upfile">
<BR>
<INPUT TYPE=SUBMIT ID="submitButton" VALUE="Submit">
</FORM>
Take note to put ENCTYPE="multipart/form-data" inside the form tag, this attribute specifies the content type used to encode the form data set for submission to the server.
What we are going here is to dynamically create an iframe, and set form's submitting target to it when submit button is clicked. Add belowing codes to header section of the html document, we will add the iframe only once, so we check the iframe's length is less than one:
<header>
***other codes ****
<!-- document javascripts -->
<script type="text/javascript">
$(document).ready(function () {
$('#submitButton').click(function(){
if($('iframe[name=iframeTarget]').length<1){
var iframe=document.createElement('iframe');
$(iframe).css('display','none');
$(iframe).attr('src','#');
$(iframe).attr('name','iframeTarget');
$('body').append(iframe);
$(this).attr('target','iframeTarget');
}
});
});
</script>
***other codes ****
</header>
If you like our tutorial, please follow us on Twitter and help spread the word. We need your support to continue.