Top

Follow me and receive all the latest free scripts:

By Email:

Categories
Most Popular Posts

Refresh an image after an ajax file upload in jQuery

Published June 20, 2015 by , category jQuery

jQueryRefreshCacheAjaxPHPMySQLRefresh an image

How to refresh an image after an ajax file upload in jQuery

Introduction

Interesting question! It happens that I got this problem recently when I was building an internet website's member section.

The member who registers and log in had to be able to upload or change his profile image. I wrote a script using Ajax and jQuery, but once I uploaded a new profile image, which always has the same name, the page was still displaying the previous image unless I clicked CTRL + F5 to refresh properly the page...and the image.

So I did some researches online and I found a solution which consists of:

Below I give you the full script including the image upload using jQuery and Ajax without refreshing page, and the image refreshment after the upload to display the correct newly uploaded image.

But first...a demo

Live demo

Add / change your profile image:

Maximum : 256 Kb

Formats accepted : jpg, jpeg

Files architecture

index.php
db.class.php

ajax

tuto-upload-refresh-image.php

jquery

js

tuto-upload-refresh-image.js

upload/image-profile

There is an "upload/image-profile" folder. It's where the image will be stored.

Database structure sample

A simple database structure sample, you can easily adapt it to your table. In this example I consider the USER with the ID 1 wants to change his profile image.

id is the "id" (database row number), an auto_increment field. user, the user ID, in our case 1. image_profile, a varchar field where the image URL will be stored.

CREATE TABLE IF NOT EXISTS `tc_tuto_upload_refresh_image` (
  `id` int(6) NOT NULL AUTO_INCREMENT,
  `user` int(6) NOT NULL,
  `image_profile` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;

INSERT INTO `tc_tuto_upload_refresh_image` (`id`, `user`, `image_profile`) VALUES
(1, 1, 'profile-1.jpeg');

Database connection

Page db.class.php. More information about the database connection I use here. You can use your own system (PDO, MySQLi) to build your own queries.

HTML code

This is the index.php page (or any page you want the script appears), I put the full page structure. Code is commented. JavaScript is at the end, before </body> markup, with a link to jquery/jquery-1.10.1.min.js and a link to js/tuto-upload-refresh-image.js.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr">
<head>
	<title>Refresh an image after an ajax file upload in jQuery?</title>
	
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	
</head>

<body>

<div id="resultImageProfile">
	<?php
	$user = $bdd->getOne('SELECT * FROM tc_tuto_upload_refresh_image WHERE user = 1'); // Get line with user 1 from database
	
	if (isset($user['image_profile']) && $user['image_profile'] != "") { // Test if image exists
		echo '<p class="myImage"><img src="/upload/image-profile/'.$user['image_profile'].'" width="100" alt="" /></p>'; // If image exists we display the image
	}
	?>
	</div>
	
	<p>
	<form method="post" enctype="multipart/form-data" id="MyImageProfileUploadForm" action=""> <!-- Our form with a file type field and a hidden field containing the user ID (here 1) -->
		<div><b>Add / change your profile image: </b></div><div><input name="imageProfile" id="imageProfile" type="file" /><input name='userId' type='hidden' value="<?PHP echo $user['id']; ?>" /></div>
	</form>
	</p>
	<p>Maximum : <b>256 Kb</b></p>
	<p>Formats accepted : <b>jpg</b>, <b>jpeg</b></p>

<script type="text/javascript" src="jquery/jquery-1.10.1.min.js"></script>
<script type="text/javascript" src="js/tuto-upload-refresh-image.js"></script>

</body>
</html>

JS code

It's the tuto-upload-refresh-image.js file. Lines are commented.

jQuery code is triggered when user select an image. Files are sent via an Ajax request to ajax/tuto-upload-refresh-image.php.

I'm using the AJAX form plugin to upload a single image.

$('#imageProfile').bind('change', function() { // jQuery on change form
	$("#resultImageProfile").html('<img src="/design/loader.gif" alt="" />');
	$('#MyImageProfileUploadForm').ajaxForm({ // AJAX form plugin to upload a single image
		url: '/ajax/tuto-upload-refresh-image.php', // Call this file to update database and send back the correct new image and URL
		dataType: 'json', // JSON farmat
		success: function(data){
			$('#resultImageProfile').html(data.text); // We display text in the div resultImageProfile tank
			$(".myImage img").load(function() { // We break the cache and force the browser to check for the image again
				$(".myImage img").attr( 'src', data.imgURL + '?dt=' + (+new Date()) );
			  }); 
		}
	}).submit();
});

PHP code

It's the ajax/tuto-upload-refresh-image.php

Lines are commented.

As you can see, for one user which upload a new profile image, the file name is always the same (profile-userID.pjeg), so the cache problem!

<?php
include('../db.class.php'); // Connection to database
$bdd = new db();
 
$acceptedExtension = Array('image/jpeg', 'image/jpg'); // Accepted extensions
$maxSize = 256000;
$destFolder = '../upload/image-profile/'; // We upload the image here
 
$imgType = $_FILES["imageProfile"]["type"];
$imgSize = $_FILES["imageProfile"]["size"];
$imgName = $_FILES["imageProfile"]["name"];
$imgTmpName = $_FILES["imageProfile"]["tmp_name"];
list($txt, $ext) = explode("image/", $imgType); // Get image extension

if (in_array($imgType, $acceptedExtension) && $imgSize <= $maxSize && $imgSize != "") { // Test is extension allowed and image size ok
 
	$newThumbImageName = 'profile-'.$_POST['userId'].'.'.$ext; // We rename the image (in our example it will be profile-1.jpeg)

	if(move_uploaded_file($imgTmpName,$destFolder.$newThumbImageName)) { // Upload image
		
		$query = $bdd->execute('UPDATE tc_tuto_upload_refresh_image SET image_profile = "'.$newThumbImageName.'" WHERE user='.$_POST['userId']); // Update database

		$text = '<p class="myImage"><img src="/upload/image-profile/'.$newThumbImageName.'" width="100" alt="" /></p>'; // Send back the image...
		$text .= '<div class="alert alert-success" role="alert">Image profile uploaded successfully.</div>'; //...and a successfull text
		
		$dataBack = array('text' => $text, 'imgURL' => '/upload/image-profile/'.$newThumbImageName); // Also send back the image URL
	}
 
} else {
	if (!in_array($imgType, $acceptedExtension)) $text = '<div class="alert alert-danger" role="alert">Wrong format! Formats accepted: jpeg, jpg.</div>';
	if ($imgSize > $maxSize) $text = '<div class="alert alert-danger" role="alert">Image too heavy. Maximum 256 Kb.</div>';
	if ($imgSize == "") $text = '<div class="alert alert-danger" role="alert">Please choose an image!</div>';
	
	$dataBack = array('text' => $text);
}

$dataBack = json_encode($dataBack);
echo $dataBack;
?>

Conclusion

Finish! You have now a complete script to upload an image, with the same file name, for a user, without refreshing page.

You may be interested by those similar scripts:

- How to upload an image using Ajax and jQuery, without refreshing page

- How to upload multiple images using PHP, Ajax and jQuery

- How to upload multiple files with drag and drop using HTML5 and jQuery

About Simon Laroche
Simon Laroche on Google+
Simon Laroche on Twitter
Simon Laroche on Facebook
Simon Laroche on Pinterest
Simon Laroche on LinkedIn
: I am a Coder, Designer, Webmaster and Expert SEO Consulting, I'm also a wise traveller and an avid amateur photographer. I created the website TipoCode and many others such as Landolia: a World of Photos...

If you need help about this script, please leave a comment below. I reply as much as I can depending of my time, you may also get help from others.
I also offer a paid support, if you are in the need to adapt or create a script...

Leave a comment

Comments (2 comments)

Suz Posted on May 19, 2016
Hi, thanks for great code, but I get some error messages.
Fatal error: Call to a member function getOne() on a non-object in ....
when calling to the database.
Something in this line: $user = $bdd->getOne('SELECT * FROM bilder_opp WHERE user = 1');
$user is not an object ???? Tried to make user an object but doesn't work.
and in the form am I supposed to link to the php file in the action=" ?????"
Please need this upload for a school project sort of asap.
Thanks.
abu Posted on March 28, 2016
need download file the example