TailTemplate Build stunning websites faster with our pre-designed Tailwind CSS templates

JQuery file posting using iframe

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.

Preparation

  • Download JQuery, in this tutorial we are using JQuery 1.4.2. Place JQuery lib into "js" directory.
  • Create a simple test page "test.html":
<html>
<head>    
    <script type="text/javascript" src="js/jquery-1.4.2.min.js">
    </script>   
</head>
<body>
</body>
</html>
  • Create a dummy backend script "upload.php", in this tutorial we are not going to talk about how to upload file in backend, so leave "upload.php" as blank.

Set up form for uploading

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.

Set up iframe for uploading

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>

The end

If you like our tutorial, please follow us on Twitter and help spread the word. We need your support to continue.