Ajax file upload in modal window

Do you publish your blogs with WordPress? If yes, you know the inline popup window which opens if you like to upload / insert an image into your article. This tutorial shows you how-to use the jQuery Plugin ThickBox and some jQuery code to upload a file and pass a value to the parent page. You can use this function in your custom CMS or maybe you like use this code snippet as the basic code for your own Ajax file upload plugin or gadget?

Scripts and libraries for the Ajax file upload

PHP Upload Class / Script
We use this PHP Script provided by our partner site finalwebsites.com because it’s very powerful and easy to use. Since the upload process is not the difficult part in this tutorial you might use your own PHP upload code instead.

jQuery JavaScript Library
There are several client side libraries available on the Internet, I like jQuery because there are many resources and cool plugins.

ThickBox – webpage UI dialog widget
I tried several Lightbox types and since a while I use the ThickBox plugin. For the upload process, we need modal window which will open as an Iframe.

Our dynamic form (form.php)

Most forms process some data for a database or they send the data within an e-mail message. In my example I have a form with just two form fields one for a name tag and one for the file name.

<form action="form.php" method="post">
	<p>
		<label for="nametag">Name</label>
		<input type="text" name="nametag" size="20" />
	</p>
	<p>
		<label for="myfile">File name</label>
		<input type ="text" id="myfile" name="myfile" readonly="readonly" />
 		 <a href="upload.php?placeValuesBeforeTB_=savedValues&TB_iframe=true&height=300&width=400&modal=true" class="thickbox">Upload</a>
 	</p>
 	<p style="text-align:right;"><input type="submit" name="Submit" value="Send" /></p>
</form>

Notice the attributes and the URL used inside the link element to our upload script. I set the ThickBox size, I enable the values for Iframe and modal. I used also some ID for the “readonly” form field which is used to store the filename after the upload is done. I added also a form action because we need to process the form afterwards.

The upload script (upload.php)

After the user has clicked the upload link, a lightbox will open an Iframe holding the upload script. This is the PHP code which is responsible for the upload process.

include_once $_SERVER['DOCUMENT_ROOT'].'/pathtotheclass/upload_class.php';
$error = '';
$img = '';
$copy_link = '';
		
if(isset($_POST['Submit'])) {
	$my_upload = new file_upload;
	$my_upload->upload_dir = $_SERVER['DOCUMENT_ROOT']."/modal-upload/files/";
	$my_upload->extensions = array(".png", ".jpg", ".gif"); // allowed extensions
	$my_upload->rename_file = true;
	$my_upload->the_temp_file = $_FILES['upload']['tmp_name'];
	$my_upload->the_file = $_FILES['upload']['name'];
	$my_upload->http_error = $_FILES['upload']['error'];
	if ($my_upload->upload()) {
		$image = $my_upload->file_copy;
		$copy_link = ' | Pass file name';
	} 
	$error = $my_upload->show_error_string();
}

You will find several example files if you download the upload class from my website. For this tutorial I will explain the most important variables and methods.

$my_upload->upload_dir
This upload directory is important, some “cheap” web hosts doesn’t allow that PHP has write access to directories. In that case you need to chmod the directory with 0777 (note, that might not safe BTW). If this directory doesn’t exists the upload will fail.

$my_upload->extensions
Allow only the extensions you need in your application, in our example we need to retrieve the image’s filename.

$my_upload->rename_file
Your users might have file names with spaces or foreign characters, use this option to rename your uploaded file to an URL-safe string.

$my_upload->file_copy
The (new) name generated by a successful upload, use this name in your further application process.

Let’s check the upload form:

<form action="upload.php" method="post" enctype="multipart/form-data">
	<p>
		<label for="upload">Select file</label>
		<input name="upload" type="file" size="15" />
		<br />
		<input type="submit" name="Submit" value="Upload" />
	</p>
</form>
<p><?php echo $error; ?></p>
<p><a href="#" onclick="self.parent.tb_remove();">Cancel</a><?php echo $copy_link; ?></p>

Because this is an upload form, you need add the “enctype” attribute “multipart/form-data”, otherwise the file will not be uploaded to your server. You see two link elements below the form, one is static to cancel/close the upload dialog and the other one is generated by PHP after the upload is done and gets the ID “closelink”. This ID is important for the following jQuery function:

$(document).ready(function() { 
	$("#closelink").click(function() {
		$("#myfile", top.document).val('<?php echo $image; ?>');
	});
});

If the user clicks the link with the ID “closelink”, the filename is passed to top document’s element with the ID “myfile” and the ThickBox gets closed. With the completed form you’re able to process the data inside the parent document. I added this php upload function on my other website, which will demonstrate the “modal effect”. If you like to use the files from this tutorial, you can download the PHP script. If you have questions or suggestions, please post them them below.

Published in: jQuery Code · PHP Scripts

6 Comments

  1. Very good tutorial. How about automatically pass the value(s) from the form after the new values are submitted(the new values will update a database table backend, the new values such as user inputted, and newly automatically ID will be passed to the parent form input fields both visible and hidden). The reason I am asking is to try to get the following done:

    1. Parent Form with two input fields, one is hidden, namely contact_name(visible), and id(hidden);
    2. contact_name: use Jquery autocomplete from a table – contacts(id, contact_name, etc) to populate the value at contact_name and hidden field – id;
    3. If there is no record matched, user click ‘add’ button next contact_name to trigger an add form for contacts. Once a new record is added, the add form closes and pass the new value of contact_name and id to populate the contact_name and id parent form;

    Can you give me any suggestions?

  2. Hi..

    Really great code.. Thanks
    I am trying to pass more variables. As i need to pass some ids with the image. But I am not able to fetch that id in upload.php..

    Please help me for this.
    Below is what i am using
    <a href="upload_room.php?placeValuesBeforeTB_=savedValues&TB_iframe=true&height=500&width=400&modal=true&rid=" class="thickbox">Upload

    Thanks
    Dhvani

Comments are closed.