9lessons programming blog
Loading Search
9lessons Bring Friends
Wall Script
Follow Me:
Tuesday, September 24, 2013

Ajax Select and Upload Multiple Images with Jquery

Very few days back I had posted an article about Multiple ajax image upload without refreshing the page using jquery and PHP. In this post I have updated few lines of code that allows to user can select and upload multiple images in single shot, thanks to Lakshmi Maddukuri for sending me a useful piece of code. Just take a quick look this live demo.

Multiple Ajax Image Upload without Refreshing Page using Jquery and PHP.


Download Script     Live Demo

Sample database design for Users.

Users
Contains user details username, password, email, profile_image and profile_image_small etc.
CREATE TABLE `users` (
`user_id` int(11) AUTO_INCREMENT PRIMARY KEY,
`username` varchar(255) UNIQUE KEY,
`password` varchar(100),
`email` varchar(255) UNIQUE KEY
)

User Uploads
Contains user upload details upload_id, image_name, user_id_fk(foreign key) and timestamp etc.
CREATE TABLE  `user_uploads` (
`upload_id` int(11) AUTO_INCREMENT PRIMARY KEY,
`image_name` text,
`user_id_fk` int(11),
`created` int(11)
)

Javascript Code
$("#photoimg").live('change',function(){})- photoimg is the ID name of INPUT FILE tag and $('#imageform').ajaxForm() - imageform is the ID name of FORM. While changing INPUT it calls FORM submit without refreshing page using ajaxForm() method. Uploaded images will prepend inside #preview tag.
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.wallform.js"></script>
<script type="text/javascript">
$(document).ready(function()
{

$('#photoimg').live('change', function()
 {
var A=$("#imageloadstatus");
var B=$("#imageloadbutton");

$("#imageform").ajaxForm({target: '#preview',
beforeSubmit:function(){
A.show();
B.hide();
},
success:function(){
A.hide();
B.show();
},
error:function(){
A.hide();
B.show();
} }).submit();
});

});
</script>
Here hiding and showing #imageloadstatus and #imageloadbutton based on form upload submit status.


index.php
Contains simple PHP and HTML code. Here $session_id=1 means user id session value.
<?php
include('db.php');
session_start();
$session_id='1'; // User login session value
?>
<div id='preview'>
</div>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaxImageUpload.php' style="clear:both">
Upload image: 
<div id='imageloadstatus' style='display:none'><img src="loader.gif" alt="Uploading...."/></div>
<div id='imageloadbutton'>
<input type="file" name="photos[]" id="photoimg" multiple="true" />
</div>
</form>

ajaxImageUpload.php
Contains PHP code. This script helps you to upload images into uploads folder and it will  rename image file into timestamp+session_id.extention format to avoid duplicates. This system will store image files into user_uploads with user session id tables
<?php
error_reporting(0);
session_start();
include('db.php');
$session_id='1'; //$session id
define ("MAX_SIZE","2000"); // 2MB MAX file size
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
// Valid image formats 
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$uploaddir = "uploads/"; //Image upload directory
foreach ($_FILES['photos']['name'] as $name => $value)
{
$filename = stripslashes($_FILES['photos']['name'][$name]);
$size=filesize($_FILES['photos']['tmp_name'][$name]);
//Convert extension into a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
//File extension check
if(in_array($ext,$valid_formats))
{
//File size check
if ($size < (MAX_SIZE*1024))
{
$image_name=time().$filename;
echo "<img src='".$uploaddir.$image_name."' class='imgList'>";
$newname=$uploaddir.$image_name;
//Moving file to uploads folder
if (move_uploaded_file($_FILES['photos']['tmp_name'][$name], $newname))
{
$time=time();
//Insert upload image files names into user_uploads table
mysql_query("INSERT INTO user_uploads(image_name,user_id_fk,created) VALUES('$image_name','$session_id','$time')");
}
else
{
echo '<span class="imgList">You have exceeded the size limit! so moving unsuccessful! </span>'; }
}

else
{
echo '<span class="imgList">You have exceeded the size limit!</span>';
}

}

else
{
echo '<span class="imgList">Unknown extension!</span>';
}

} //foreach end

}
?>


db.php
Database configuration file, just modify database credentials.
<?php
$mysql_hostname = "localhost";
$mysql_user = "username";
$mysql_password = "password";
$mysql_database = "database";
$prefix = "";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Opps some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong");
?>

CSS
Style for image blocks.
#preview
{
color:#cc0000;
font-size:12px
}
.imgList
{
max-height:150px;
margin-left:5px;
border:1px solid #dedede;
padding:4px;
float:left;
}
Comments
{ 63 comments }
Amila said...

Thanks :)

RoseHosting said...

Thanks for sharing, this is a good example for Ajax upload.

Dropzone.js is another good script for multiple file upload.

Anonymous said...

when its necessary to use singleton and this connection?

coul'd you please maybe use mysqli in the future examples... i have a problem with singleton class =(

Manuel Ruiz said...

Please develop a ranking system for points

Ahmad Rasheed said...

The script can not be downloaded. Although I registered for Box but it says that you do not have permissions to download this file. Can you help? I am using the older version of this script on one of my websites and it's doing great!

Mr.Bình said...

box.com limit download.
You can upload mediafire.com

Anand said...

oh man.. you are amazing :)

Bharath Chowdary Maddukuri said...

Nice Lakshmi maddukuri thanks Srinivas tamada

Srinivas Tamada said...

@Ahmad Rasheed Which country you from?

Bikash Bhol said...

nice

Bikash Bhol said...

thanks

M Venkata Lakshmi said...

Thank you@srinivas Tamada

sunny said...

thanks nice work..i have a questions?. does this code will work for cross domain

Mathan raj said...

Nice one. But didn't work for IE9. :-(

Pritesh Kumar Jha said...

Hi Srinivas, i am commenting first time for your post.i am a fan of your posts.it helps a lot..i needed this kind of functionality for one of my project and i want to extend it a bit more..that is how can i remove an uploaded image at the same time without refreshing the web page.?...Although i am trying to do this , however your guidance will always be appreciated..Thanks.

Shail paras said...

Nice job...but can u add uploading process bar for all multiple image with its uploaded percentages on it? so that user can see the complete process?

Programming Zeal said...

Great work

Satish said...

Great article but dont work in IE :(

Ricky said...

I usually using uploadify. But i thing your script is better, because pure Javascript, no need Flash. Thanks.

Enyika said...

Weldone, this really help. try implement deleting of the images using check box.

Anonymous said...

For version 1.9 of jQuery
Is it possible to use the function. On () instead of live. () Is deprecated

shalini shrotriya said...

thanks

nandalal s said...

thanks ....

nandalal s said...

Thanks for d info..

Manish Jangir said...

Very nice and helpful tutorial. could we use drag and drop in this same code also??

Bharath Chowdary Maddukuri said...

Nice Work Venkata Lakshmi(Suneetha) Keep it up....

sarath said...

Good work Venkata Lakshmi(Suneetha)Keep it up...

Sai said...

This code has made my work easy! Thanks a lot Srinivas anna!! :)

Merrick Lee said...

This script is beautiful! Worked perfect

Pramod said...

Thanks for sharing this amazing tutorial with us Srinivas . This post has helped me to learn something new today . I'll be trying this out for sure.

-Pramod

devtools.korzh said...

Thanks for your share!

Kaiz said...

Nice.. What about the same but with backbone, underscore and java?

Anup said...

Wow!!! Very Nice thanks for sharing this with us.

Duy Trần said...

jQuery("#imageform").ajaxForm is not a function.
Help me. because I have use jQuery to not conflict, so i dont use $

LostPrincess said...

Thanks for this awesome script...it's realy helpfull.
And i have a suggestion: it would be great if you add "delete image" function ..
:)
Thank you very much

Mik said...

Hi! Thanks for this tute. I have an issue when uploading large files
I've got this error message: "Something went wrong."
I've checked the servers upload and post limits and are ok. Modified the Max upload size to 5mb, and still got the error.

NIYIGENA Jean Pierre said...

hi,
the plugin is great but id doesnt work in IE (totally doent work) and Safari (if more than one picture is uploaded),is there any way around?
thx

Juan Cruz said...

Thanks for the tutorial !! I really like all your scripts !!

muntasir ketwaroo said...

hello , is it possible to limit the amount of image displayed ?

mohammad reza said...

thanks for tutorial!!!
how can i use javascript alert() function and show image url with alert()????

Anonymous said...

Thanks

Navneet Jha said...

@Srinivas Tamada Hi As you are a great programmer I am requesting you to create a photo tagging script ... If you can please make it ... Thanks ...

LogoArt.vn said...

I don't want to move files before submit form, but i still want to preview. How to do it?

LogoArt.vn said...

More a question: How to add field "title" and "description" for each images before submit form?

Thank you!

Aiken said...

thanks for this tut, maybe u can extend this script with a delete function :)

Le Cuong said...

Thanks you

Le Cuong said...

Thanks you!

Anonymous said...

thanks

Rahul said...

Thanks Srinivas.It saves me hours of time to implement this kind of functionality in my website.

Anonymous said...

it works only for the first time but not for the next I dont know what is the mistake i am doing could anyone help me

Anonymous said...

Good Tutorial

Anonymous said...

Great code............

Ramesh Dura said...

Great code, Thanks!!!
i am using this code in my localhost, everything is working great.

*but sometimes the files are uploaded twice. it seems like its stuck into some kind of loop or the button is pressed twice. :S

jobinblancaflor said...

this is great

CaribeSoft said...

Hi:
Nice tutorial and nice combination.
How can I avoid this error : TypeError: Cannot read property 'msg' of undefined
I tried with required and ng-minlength="1" but it does not work.
I want to avoid to insert an "undefined" record in the table, how cna I do that?
Best regards,

Anonymous said...

very nice. For Naveent here is the photo tag script:
http://net.tutsplus.com/tutorials/php/creating-a-photo-tag-wall-with-twilio-picture-messaging-php/

Anonymous said...

works fine but its only store 1 image to mysql table...

vineetsaini said...

I want to upload 5 images one by one ? Please tell me how to do this ?

nicole kidman said...

nice work but i have problem with Arabic name image can help me thanks

Phan Văn Sơn said...

Hi, please forgive me ignorance I'm very new to javascript. Is it possible to direct the images to different tags? Such as #preview1, #preview2, etc. I'm trying to put images in different table cells. I can put div preview1, preview2 etc in the table cells but can't get the images to go there. Thanks

Moheimen Ahmed said...

That really worked with mysql php just as i wanted ... thanx a ton :D

Comprar en China said...

Thanks for your support !!
Hugs from Argentina !!

Savita Kumthe said...

Thanks for your support !!

Post a Comment