SnapShooter Backups Server, Database, Application and Laravel Backups - Get fully protected with SnapShooter

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.


  • 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":
    <script type="text/javascript" src="js/jquery-1.4.2.min.js">
  • 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">
	<INPUT TYPE=SUBMIT ID="submitButton" VALUE="Submit">

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:


***other codes ****

<!-- document javascripts -->	 
<script type="text/javascript">
$(document).ready(function () {
		    var iframe=document.createElement('iframe');

***other codes ****


The end

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