By Sam Deering

Show Thumbnail of Image Upload AJAX/PHP

By Sam Deering


Update 18/11/2012: The new version of this upload is now here JQUERY AJAX IMAGE UPLOAD THUMBNAIL EXAMPLE.

This is how you can add a file/image upload tool to your forms and have AJAX store the file with PHP and return a thumbnailed version to the user for display on the form. Nice.

How it works

  1. User selects a file/image from the form input field
  2. jQuery sends an AJAX request with the file/image
  3. PHP creates a thumbnail version and sends back the url in JSON format
  4. jQuery displays the thumbnailed version on the form


  • doajaxfileupload.php
  • ajaxfileupload.php
  • jquery.php
  • form-html.php

Download Source FilesSee Live Demo

The jQuery Code – jquery.js

function previewImage(str) {

function removeImage() {
	//alert("Image Removed");
	var tid = $("Input[name=allocatedimagename]").val();
	//remove the temporary image files created by the image
	$.get("/php/deleteblogthumb.php",{thumb_name: tid, type: 'js-blog'}, function(data){


function ajaxFileUpload() {
    //starting setting some animation when the ajax starts and completes
        prepareing ajax file upload
        url: the url of script file handling the uploaded files
                    fileElementId: the file type of input element id and it will be the index of  $_FILES Array()
        dataType: it support json, xml
        secureuri:use secure protocol
        success: call back function when the ajax complete
        error: callback function when the ajax failed
            dataType: 'json',
            success: function (data, status)
                if(typeof(data.error) != 'undefined')
                    if(data.error != '')
                        //show the preview of image
						var imageloc = 'Your uploaded image: ''('+data.size+'kb)'+'
your uploaded image
'; $("#imagethumb").html(imageloc); //add $("#removebutton").show(); $("#supportedfiles").hide(); //save the allocated image name for use with the process signup script $("Input[name=allocatedimagename]").val(data.loc); } } }, error: function (data, status, e) { alert(e); } } ) return false; }

The jQuery Code – ajaxfileupload.js


    createUploadIframe: function(id, uri)
			//create frame
            var frameId = 'jUploadFrame' + id;
            if(window.ActiveXObject) {
                var io = document.createElement('');
                if(typeof uri== 'boolean'){
                    io.src = 'javascript:false';
                else if(typeof uri== 'string'){
                    io.src = uri;
            else {
                var io = document.createElement('iframe');
       = frameId;
       = frameId;
   = 'absolute';
   = '-1000px';
   = '-1000px';


            return io			
    createUploadForm: function(id, fileElementId)
		//create form	
		var formId = 'jUploadForm' + id;
		var fileId = 'jUploadFile' + id;
		var form = $('
'); var oldElement = $('#' + fileElementId); var newElement = $(oldElement).clone(); $(oldElement).attr('id', fileId); $(oldElement).before(newElement); $(oldElement).appendTo(form); //set attributes $(form).css('position', 'absolute'); $(form).css('top', '-1200px'); $(form).css('left', '-1200px'); $(form).appendTo('body'); return form; }, ajaxFileUpload: function(s) { // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout s = jQuery.extend({}, jQuery.ajaxSettings, s); var id = new Date().getTime() var form = jQuery.createUploadForm(id, s.fileElementId); var io = jQuery.createUploadIframe(id, s.secureuri); var frameId = 'jUploadFrame' + id; var formId = 'jUploadForm' + id; // Watch for a new set of requests if ( && ! ) { jQuery.event.trigger( "ajaxStart" ); } var requestDone = false; // Create the request object var xml = {} if ( ) jQuery.event.trigger("ajaxSend", [xml, s]); // Wait for a response to come back var uploadCallback = function(isTimeout) { var io = document.getElementById(frameId); try { if(io.contentWindow) { xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null; xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document; }else if(io.contentDocument) { xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null; xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document; } }catch(e) { jQuery.handleError(s, xml, null, e); } if ( xml || isTimeout == "timeout") { requestDone = true; var status; try { status = isTimeout != "timeout" ? "success" : "error"; // Make sure that the request was successful or notmodified if ( status != "error" ) { // process the data (runs the xml through httpData regardless of callback) var data = jQuery.uploadHttpData( xml, s.dataType ); // If a local callback was specified, fire it and pass it the data if ( s.success ) s.success( data, status ); // Fire the global callback if( ) jQuery.event.trigger( "ajaxSuccess", [xml, s] ); } else jQuery.handleError(s, xml, status); } catch(e) { status = "error"; jQuery.handleError(s, xml, status, e); } // The request was completed if( ) jQuery.event.trigger( "ajaxComplete", [xml, s] ); // Handle the global AJAX counter if ( && ! ) jQuery.event.trigger( "ajaxStop" ); // Process result if ( s.complete ) s.complete(xml, status); jQuery(io).unbind() setTimeout(function() { try { $(io).remove(); $(form).remove(); } catch(e) { jQuery.handleError(s, xml, null, e); } }, 100) xml = null } } // Timeout checker if ( s.timeout > 0 ) { setTimeout(function(){ // Check to see if the request is still happening if( !requestDone ) uploadCallback( "timeout" ); }, s.timeout); } try { // var io = $('#' + frameId); var form = $('#' + formId); $(form).attr('action', s.url); $(form).attr('method', 'POST'); $(form).attr('target', frameId); if(form.encoding) { form.encoding = 'multipart/form-data'; } else { form.enctype = 'multipart/form-data'; } $(form).submit(); } catch(e) { jQuery.handleError(s, xml, null, e); } if(window.attachEvent){ document.getElementById(frameId).attachEvent('onload', uploadCallback); } else{ document.getElementById(frameId).addEventListener('load', uploadCallback, false); } return {abort: function () {}}; }, uploadHttpData: function( r, type ) { var data = !type; data = type == "xml" || data ? r.responseXML : r.responseText; // If the type is "script", eval it in global context if ( type == "script" ) jQuery.globalEval( data ); // Get the JavaScript object, if JSON is used. if ( type == "json" ) eval( "data = " + data ); // evaluate scripts within html if ( type == "html" ) jQuery("
").html(data).evalScripts(); //alert($('param', data).each(function(){alert($(this).attr('value'));})); return data; } })

The PHP Code – doajaxfileupload.php

$ratio2)	{
        else	{

          // we create a new image with the new dimmensions

        // resize the big image to the new created one

        // output the created image to the file. Now we will have the thumbnail into the file named by $filename

          //destroys source and destination images.

       // This function reads the extension of the file.
       // It is used to determine if the file is an image by checking the extension.
       function getExtension($str) {
               $i = strrpos($str,".");
               if (!$i) { return ""; }
               $l = strlen($str) - $i;
               $ext = substr($str,$i+1,$l);
               return $ext;

        //reads the name of the file the user submitted for uploading

 	// if it is not empty
 	if ($image)
 		// get the original name of the file from the clients machine
 		$filename = stripslashes($_FILES[$fileElementName]['name']);

 		// get the extension of the file in a lower case format
 	 	$extension = getExtension($filename);
 		$extension = strtolower($extension);
 		// if it is not a known extension, we will suppose it is an error, print an error message
 		//and will not upload the file, otherwise we continue
 		if (($extension != "jpg")  && ($extension != "jpeg") && ($extension != "png"))
 			$error .= 'Unknown extension!';
 			// get the size of the image in bytes
 			// $_FILES['image']['tmp_name'] is the temporary filename of the file in which
			//the uploaded file was stored on the server

 			//compare the size with the maxim size we defined and print error if bigger
 			if ($sizekb > MAX_SIZE*1024)
 				$error .= 'You have exceeded the size limit!';
 			else {

              //we will give an unique name, for example the time in unix time format
            //the new name will be containing the full path where will be stored (images folder)
            $copied = copy($_FILES[$fileElementName]['tmp_name'], $newname);
            //we verify if the image has been uploaded, and print error instead
            if (!$copied)
              $error .= 'Copy unsuccessfull!';
              // the new thumbnail image will be placed in images/thumbs/ folder
              // call the function that will create the thumbnail. The function will get as parameters
              //the image name, the thumbnail name and the width and height desired for the thumbnail

              //also add the users pic


      //--------- END SECOND SCRIPT --------------------------------------------------------------------

      //return variables to javascript
			$filename = $_FILES[$fileElementName]['name'];
			$filesize = round(($sizekb/1000), 0);
			$fileloc = $thumb_name;
			//for security reason, we force to remove all uploaded file
	$return_JSON = "";
	$return_JSON .= "{";
	$return_JSON .=				"error: '" . $error . "',n";
	$return_JSON .=				"name: '" . $filename . "',n";
	$return_JSON .=				"size: '" . $filesize . "',n";
	$return_JSON .=				"loc: '" . $fileloc . "'n";
	$return_JSON .= "}";
	echo $return_JSON;

The HTML Code


Supported file types: jpg, jpeg, png (max 1mb)
Your image will be resized to 110 by 110 px (40 by 40 for blog thumbs)

  • Pingback: Show Thumbnail of Image Upload AJAX/PHP « Big Engine Media()

  • kailash malav

    Code is great according to functionality , but not correctly running in my local host please give suggestion how to use that code…..thanks for sharing it with us .

  • jquery4u

    Hi Kailash,

    Yes it seems i have missed something in the download package. When i get some spare time i’ll update the demo files and fix it up.

    Very sorry about this.


    • mike

      any word on the fix yet? i was reading through the code and dont see anything wrong.

      • jquery4u

        Hi Mike, there’s nothing wrong with the code. It is working on my BLOGOOLA site. I just need to recompile the download package. Also I can’t post my recapcha keys as they are private so when you download you’d have to add in your own keys.

    • sartaj

      the idea is very nice.
      this is what i want but i too want it in my local system what are the keys i changed? please help me!

  • Sankars


    nice script.
    this is only single image how do it multiple image?

    • jquery4u

      Hi Sankers, I guess it would be possible to do a multiple image version. If I was to do one I would probably just store and array (an object of key-value pairs of data) using and this would contain key value pairs for timestamp and image url respectively. The image url would be the temporary place you stored it on your server using PHP. From there you could just keep appending as many images as you like into the HTML form. Maybe add a small remove button for each image so the user could add and remove as they please. Hope this helps. If I get the time i’ll draw up an example. Cheers. Sam

      • Fish

        hello jQuery4u,
        After I downloaded your code, I modified codes to upload (multi-image) and review uploaded image , save it to database and delete image. But I have something error. For eg. when i upload 3 images, it is ok for show as 3 thumbnails and save them to file. when i delete one of them, it is also ok for delete it (it is really delete in file) but it’s not still to show another 2 thumbs (it is not delete in file). I think they should be see as thumbnails.
        Here is my code. Pls check for me.

        index.php –
        function removeImage(e) {

        var fid = $(e).attr(“fileid”);
        var tid = $(e).attr(“location”);


        //remove the temporary image files created by the image

        $imagethumb = tid;
        type: ‘POST’,
        data: {
        action: ‘deleteimage’,
        //imagefile: $imagefile,
        imagethumb: $imagethumb,
        url: ‘script.php’,
        success: function() {
        $(‘. ‘+fid).remove();


        return false;

        script.php –

        And I want to send u my codes with email because I want to share my modified codes to other ppl from your website via you.
        You are my teacher !!! :D thank you very much …. and sry for my weak english.

        • Fish

          i missed script.php code ..

  • dmitry

    doesn’t work on local, missing some files (deleteblogthumb.php)

    • jquery4u

      Hi dmitry,
      I have uploaded the missing file: deleteblogthumb.php for you.
      When I have time I will update the whole package. It’s a pretty complex bit of coding.

      • Mursel

        Hi jquery4u,

        Nice and Great script. I am Waiting for the updated package.

      • Fish

        Hi jquery4u,
        is it missing file : phpfunc-myinclude.php (require_once(“phpfunc-myinclude.php”); in phpfunc-deleteblogthumb.php)?
        And my script is not working. pls check. thanks..
        function removeImage(e) {
        //alert(“Image Removed”);
        var fid = $(e).attr(“fileid”);
        var tid = $(e).attr(“location”);
        //var tid = $(e).attr(“location”);
        //remove the temporary image files created by the image
        $.get(“phpfunc-deleteblogthumb.php”,{thumb_name: tid, type: ‘js-blog’}, function(data){

        //return false;

  • abyz

    you are great …

  • Mike

    Hi, this doesn’t work for me, it just shows a textarea under the file input, am i doing something wrong?

    • jquery4u

      @abyz – thanks!

      @Mike – have you got an example of what you mean? whats your website?

      • Mike

        Thanks for replying, yeah i’m trying testing it using xampp, i kept all the folders on here in htc doc and added a folder called images and a subfolder called thumbs.
        Is there anything i have to add to the code? pls help me out.

  • Hi Grate, these script does not works in my local machine.
    I am using wampp.

    My folder contains,

  • I can not get it to work ;-(
    The form is showing, but not the image when selected.
    What am I doing wrong? Please advice…

    Many thanks

    • jquery4u

      @Arnout – Doesn’t look like you have a change event on your browser box! So when the image is selected it calls the upload script.

  • Hi,

    i have a one problem when integrate your code to mine also when i run your code individual also i got the error

    when integrate to mine i got the javascript error
    like $.ajaxfileupload is not a function in jquery.js

    when run ur code individual i got the error alert like “SyntaxError: missing } in XML expression”

    please help what is the error

    • Hi i fix the problem now and i have another problem today. when i upload a png images the “imagecreatefrompng” through the error also i can’t able to upload the gif images .

      • jquery4u

        @Karuppasamy – Whats the error message say? Is the error in PHP or front-end?

        • hi sir i have same problem to SyntaxError: missing } in XML expression, what should i do?

          • sorry finally i fix the problem, just put ; after $(“#loading”) …. but now i have new problem same as mr. arnout form is showing, but not the image when selected. am i miss something? emm Is this because of my browser (fire fox) didn’t read event onChange=”javascript:previewImage(this.value)”?
            sorry for my english.. thangkyu sir

  • Lukas

    Can anybody give me an advice how to solve this issue with by using the given script? Or don’t you know whether it is somewhere solved?
    I have four images – each in another part of layout (so it shouldn’t be a multiple upload with using arrays of information).
    I would like to upload thumbnail of none, 1, 2, 3 or 4 of them into a form, that is then send normally by PHP.
    I tried to use 4 instances of given scripts but this made me a lot of troubles.
    Can anybody help me?

  • I get a “{error: ‘No file was uploaded..’, name: ”, size: ”, loc: ” }” above the choose file button, and a strange input box below:

    What can I do?

  • pietro

    it’s possible hava a complete working necessary? (all files?)

  • helped me a lot in my website…
    ajax is tricky
    so i used

    here is a demo

  • but i still cannot find ways to improve the image quality…

  • pushpa

    I used the same plugin. Images are uploading in firefox but it is not happening in other browsers. I am not getting the file parameters in other browsers. What might be the issue?

    • jquery4u


      Have you got an example mate? I would start by checking the data that is returned by the PHP. Check the syntax as Firefox may be able to handle a slight syntax error. Also how are you appending the images to the page?


  • I have a problem. It’s not working on IE. It doesn’t upload the image at all.

    • jquery4u

      @Site Status,

      It’s does work in all versions of IE. Have you got the url where your trying to do this?


      • Hi,
        Plugin is great, but it doesn’t work in IE. First image is uploading and show in browser, but i can’t change it on another. I have used IETester. Results equal for local and your demo.

  • Pingback: 10 jQuery File Uploads | jQuery4u()

  • mayfield

    hi, i have javascripts problem:
    – cannot read property ‘body’ of undefined
    – cannot read property ‘error’ of undefined

    what might be the issue?

    • Hi Mayfield, never seen that before! What code are you using? Can you share a screeshot?

  • Natalia

    This looks like a very nice script. I haven’t tried it yet, but already have a question :)
    I am using Zend framework and Smarty templates. I have a file upload that is in the form, and right now everything works fine, meaning the file is getting saved to a proper location as the other inputs form a form. I need to add a thumbnail preview of an image. My question is, will the AJAX upload, the way it is here, interfere with the saving of the file that I have now. I will be trying anyway, so will let you know whatever is happening :)
    I hope I explained well enough :)
    Thank you for your time.

    • Hi Natalia, yes the file upload method here works differently, it uploads the image and creates a thumbnail which the url is returned and displayed to the user. Then on form submit the image url is passed to the backend where the uploaded image is renamed and filename stored in the database. I have used Smarty heaps before and it will work well with this image upload method. I’ll see if I can piece together some code for you.

  • fucku

    this is so useless

  • Zohra S

    Sam, there are multiple issues here for the newest IEs, and one even for chrome.

    IE freaks out for the createUploadFrame function, because it just doesn’t understand this:

    var io = document.createElement(”);

    And, the second issue is if you’re using this script just to display a resized version of the image, the initial form doesn’t send in the actual image in IE or Chrome. The field becomes empty.

    Any clues?

    • Hi Zohra, I’ve done a revised version of this script and will post on the blog in next couple of days. It should resolve these issues.

  • inearza

    open demo site have trojan ?

  • sean

    hello to all, I’ve tried to use this scipt in my post ad form, it is not working.

  • kaore

    I just wrote up an article describing how to do this without jquery and using an iframe here:

  • arminder

    hi …

    nice script

    thanks a lot

  • Jaideep Kumar

    same process i have done but there is an error occur
    error name: TypeError: jQuery.handleError is not a functionjQuery.handleError(s, xml, status, e);in ajaxfileupload.js
    how to solve plz help me??

Get the latest in JavaScript, once a week, for free.