Upload Image with jQuery Ajax



Image upload without refreshing the page is commonly used by websites. So today I am going to show you how it is easy to implement upload image with jQuery AJAX. On a single click you will be able select file from the popup window and on select the image will upload and you will see the image on the same page.

I have used a jQuery plugin AjaxUpload, PHP file upload script and some simple jQuery code.

<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/ajaxupload.js"></script>

Now we need a simple html code to upload an image and show the result. Also we need some css code to style the upload button like below:

<style>
.upload{background:#CCCCCC; border: 2px solid #F0B21E; color: #1F93EC; font-size: 28px; padding: 10px 15px; width: 167px;}
</style>

<div id="imageupload" class="upload">Upload Image</div>
<div class="status"></div>
	
<div class="result" >
	Result: <br/><br/>
<span id="images"></span>
</div>

Now we need to add following jQuery script to upload the selected image. It will enable imageupload to upload an image and call a php script ‘upload.php’ to save the file.

$(function(){
	var file_type = '';
	var btnUpload=$('#imageupload');
	var status=$('.status');
	new AjaxUpload(btnUpload, {
		action: "upload.php",
		//Name of the file input box
		name: 'uploadfile',
		onSubmit: function(file, ext){
			file_type = ext;
			status.html('uploading....');
		},
		onComplete: function(file, response){
			
			//On completion clear the status
			status.html('');
			//Add uploaded file to list
			if(response==="upload_error"){
				alert("Error in upload");
			} else{
				
				var imgHtml = '<br /><br /><div><img src="uploads/'+response+'" /></div>';
				
				$("#images").append(imgHtml);
			}
		}
	});
	
});

If the file uploaded successfully it will append the uploaded image to images else will alert “Error in upload”. PHP file ‘upload.php‘ has the following script to upload image on server.

if(!$_FILES['uploadfile']['error']){
	$uploaddir = $_SERVER['DOCUMENT_ROOT'].'/ajaxupload/uploads/'; // change this
	
	$file = $_FILES['uploadfile'];

	$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
	$ext = strtolower($ext);
	$fileName = uniqid(time(), false).'.'.$ext;
	$destinationfile = $uploaddir . $fileName;
	if(move_uploaded_file($file['tmp_name'], $destinationfile)){
		echo $fileName;
	} else {
		echo 'upload_error';
	}
} else {
	echo 'upload_error';
}

You can use this as multiple upload files but one by one. This is a simple way to upload an image with jQuery ajax using a plugin without reload the page.

Live Demo   Download Script

Upload Image with jQuery Ajax
Upload Image with jQuery Ajax