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.

Smarter Web Hosting
Hosting for developers - Free Trial!

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 = ' | <a id="closelink" href="#" onclick="self.parent.tb_remove();">Pass file name</a>';
	} 
	$error = $my_upload->show_error_string();
}

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

$my_upload->upload_dir
This upload directory is important, while many web hosts don’t allow that PHP has write access to directories, you need to chmod the directory with 0777. 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 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 at finalwebsites.com. If you have questions or suggestions, please post them them below.

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 Richard,

    I this you can pass the new value with a similar function like

    $("#myfile", top.document).val('< ?php echo $image; ?>');

  3. how can display the $image?

  4. Hello Tia, please describe your problem a little bit more. Thanks

  5. Hi, thanks for answer me so quickly.
    I want to know how display (show) the image (that i’ve uploaded in the thickbox ) in the form.
    Thnx

  6. okay, create on that page a DIV container with the ID “theDiv”

    and use this code:


    $("#myfile", top.document).val('');

    with

    $('#theDiv').prepend('<img id="theImg" src="" />');

    Maybe you need to fix the image path

  7. (sorry)
    Hey Olaf.
    Well, i tried doing this :

    (upload.php)

    ———$(“#theDiv”).prepend(“bu”);
    (form.php)

    ———
    and even like that , it didnt work out.

  8. in the form.php class i create DIV with id “The Div”

  9. Tia, you need to use exact the same name.
    I will add the function to the demo page over a few minutes. Forget the demo :)

    #1 create on the page where the image has to appear this tag:

    and inside the pop-up page you need to have this code:

    $(document).ready(function() { 
    	$("#closelink").click(function() {
    		$("#theDiv", top.document).prepend('<img id="theImg" src="<?php echo $image; ?>" />');
    	});
    });

    It seems like that WordPress has stripped some important code in my previous answer :)

  10. hey!!! now it DOES work. I think there was something wrong with my image path.

    Thank you so much!!!

  11. You’re welcome Tia!

  12. 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

  13. Hi, you need to place your vars before the this one “placeValuesBeforeTB_”

  14. Hi Cool script… how can I do this with colorbox (http://www.jacklmoore.com/colorbox) instead of thickbox?

  15. Hi Eli, never used the colorbox plugin, but I think it should work like described in this FAQ section:
    http://www.jacklmoore.com/colorbox/faq#faq-parent

Because of all the spam attemps I've decided to close the comment form at this time. If you have have any questions or comments please post them by using Google+ or Twitter (the links to my profiles are located at the top of this page).