Ajax file upload PHP / jQuery Tutorial

The asynchronous file upload, using some XMLHttpRequest (Ajax), is technically not possible. Most JavaScript examples and tutorials call this method still Ajax upload and the image or file is uploaded by using a “virtual IFRAME”. Anyway it’s still user friendly way to provide an upload function for your visitors or users.

In this quick tutorial I will show your how-to create such an Ajax image upload form using the jQuery Form plug-in and my PHP upload class. There is also an Ajax upload demo page which will show how it really works.

The scripts are very simple, build your image upload form just like normal. In place of posting the form data to a PHP script, you will use some JavaScript code to post the data to a PHP script in the background.

Requirements

Download the full example code

Ajax file upload PHP tutorial code

Download the required files and place the JavaScript files into the same directory as your HTML document and place the following JavaScript code into the HTML header:

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() {
	$("#loading").ajaxStart(function(){
		$(this).show();
	}).ajaxComplete(function(){
		$(this).hide();
	});
	var options = {
		beforeSubmit:  showRequest,
		success:       showResponse,
		url:       'upload4jquery.php',  // your upload script
		dataType:  'json'
	};
	$('#Form1').submit(function() {
		$('#message').html('');
		$(this).ajaxSubmit(options);
		return false;
	});
}); 
function showRequest(formData, jqForm, options) {
	var fileToUploadValue = $('input[name=fileToUpload]').fieldValue();
	if (!fileToUploadValue[0]) {
		$('#message').html('Please select a file.');
		return false;
	} 
	return true;
} 
function showResponse(data, statusText)  {
	if (statusText == 'success') {
		if (data.img != '') {
			$('#result').html('<img src="/upload/thumb/'+data.img+'" />');
			$('#message').html(data.error);
		} else {
			$('#message').html(data.error);
		}
	} else {
		$('#message').html('Unknown error!');
	}
} 
</script>

Next create a PHP script named “upload4jquery.php” and place it in the same directory where the other files are located. Place this code into your PHP file:

<?php
include($_SERVER['DOCUMENT_ROOT'].'/classes/upload/foto_upload_script.php');
$foto_upload = new Foto_upload;	
$json['size'] = $_POST['MAX_FILE_SIZE'];
$json['img'] = '';
$foto_upload->upload_dir = $_SERVER['DOCUMENT_ROOT']."/upload/";
$foto_upload->foto_folder = $_SERVER['DOCUMENT_ROOT']."/upload/";
$foto_upload->thumb_folder = $_SERVER['DOCUMENT_ROOT']."/upload/thumb/";
$foto_upload->extensions = array(".jpg", ".gif", ".png");
$foto_upload->language = "en";
$foto_upload->x_max_size = 480;
$foto_upload->y_max_size = 360;
$foto_upload->x_max_thumb_size = 120;
$foto_upload->y_max_thumb_size = 120;
$foto_upload->the_temp_file = $_FILES['fileToUpload']['tmp_name'];
$foto_upload->the_file = $_FILES['fileToUpload']['name'];
$foto_upload->http_error = $_FILES['fileToUpload']['error'];
$foto_upload->rename_file = true; 
if ($foto_upload->upload()) {
	$foto_upload->process_image(false, true, true, 80);
	$json['img'] = $foto_upload->file_copy;
} 
$json['error'] = strip_tags($foto_upload->show_error_string());
echo json_encode($json);
?>

This tutorial or guide is not about how to use the PHP upload class. If you never used the class before, than try the example files first and try than the Ajax upload form.

Paths and upload directories

You need to create two upload directories: One for the upload main file and one for the thumbnails. Check/change the permission for the directories (CHMOD the directories with 0755). If you use the same structure as suggested in the PHP class file, there is no need to change the includes at the top of the PHP script.

Now we need to create the form HTML and some other containers where the response data will be placed.

<form id="Form1" method="post" action="">
    <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_size; ?>" />
    Select an image from your hard disk:
    <div>
        <input type="file" name="fileToUpload" id="fileToUpload" size="18" />
        <input type="Submit" value="Submit" id="buttonForm" />
    </div>
</form>
<img id="loading" src="loading.gif" style="display:none;" />
<p id="message"></p>
<div id="result"></div>

The file loading.gif is the upload indicator image, pick the file I’ve used on the demo page or check Google for other stylish images or use an online image generator.

Some final note, the code works as it is. Don’t change variable names or form field attributes, if you’re not sure how to change them inside your JavaScript code.

This (older) Ajax file upload PHP tutorial was posted at finalwebsites.com previously, I updated the code and I think this blog is a much better place. 

Published in: PHP Scripts

1 Comment

  1. Hi Olaf Lederer,
    You have written a nice tutorial on file uploading.

    I have little suggestion,
    It better to use a type button instead of type submit and call your form submit block code on button click.

Comments are closed.