Ajax Select and Upload Multiple Images with Jquery
Wall Script
Follow Me:
Monday, September 23, 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").on('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/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.wallform.js"></script>
<script type="text/javascript">
$(document).ready(function()
{

$('#photoimg').on('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;
}

91 comments:

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

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

    ReplyDelete
  2. 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 =(

    ReplyDelete
  3. Please develop a ranking system for points

    ReplyDelete
  4. 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!

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

    ReplyDelete
  6. Nice Lakshmi maddukuri thanks Srinivas tamada

    ReplyDelete
  7. @Ahmad Rasheed Which country you from?

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

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

    ReplyDelete
  10. 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.

    ReplyDelete
  11. 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?

    ReplyDelete
  12. Great article but dont work in IE :(

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

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

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

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

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

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

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

    ReplyDelete
  20. This script is beautiful! Worked perfect

    ReplyDelete
  21. 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

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

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

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

    ReplyDelete
  25. 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

    ReplyDelete
  26. 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.

    ReplyDelete
  27. 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

    ReplyDelete
  28. Thanks for the tutorial !! I really like all your scripts !!

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

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

    ReplyDelete
  31. @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 ...

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

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

    Thank you!

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

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

    ReplyDelete
  36. 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

    ReplyDelete
  37. Great code............

    ReplyDelete
  38. 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

    ReplyDelete
  39. 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,

    ReplyDelete
  40. 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/

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

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

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

    ReplyDelete
  44. 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

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

    ReplyDelete
  46. Thanks for your support !!
    Hugs from Argentina !!

    ReplyDelete
  47. Gan, javascript give me alert"Something wentaaa wrong"?? Please help me :((

    ReplyDelete
  48. Please Help. i have add Progress Bar this Script.

    ReplyDelete
  49. Hi savita, i am having issues using this script with codeIgniter. can you help?

    ReplyDelete
  50. thanks dude.you done a good job

    ReplyDelete
  51. i have this script run the localhost than get this error

    B

    ReplyDelete
  52. 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

    ReplyDelete
  53. Sorry frnd i am new in this professional so i cannot undestand this code which one is given below
    what is this $str and $l = strlen($str) - $i;
    i know that strlen is used for find string length but now hun es vich kon se length find karne hai Plz help me
    ------
    function getExtension($str)
    {
    $i = strrpos($str,".");
    if (!$i) { return ""; }
    $l = strlen($str) - $i;
    $ext = substr($str,$i+1,$l);
    return $ext;
    }
    ----

    ReplyDelete
  54. hi this is kumar...when i upload file in localhost it is showing something went wrong pop up can u please help me

    ReplyDelete
  55. Looking for this tutorial...!!!! Very Well written

    But I need to ask one thing that can we use dropzone.js with the code given in the post ?

    ReplyDelete
  56. This is very nice tutorial Do you have any Codeigniter related with this process

    ReplyDelete
  57. hi how to upload upto 1000 files in one go thank you

    ReplyDelete
  58. hi..this is good...but after i download your script and testing i got the alert as "something went wrong". Could you please help me...

    ReplyDelete
  59. you just check database file in his folder and update as per your database and create table in your database as this script required. this code run properly i checked..

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

    ReplyDelete
  61. could you please tell me how to use this code in codeigniter .... where am I supposed to add "ajaxImageUpload.php".

    ReplyDelete
  62. nice tutorial ...

    Sir i want to edit image from database . ... and update image in database plz help me

    ReplyDelete
  63. Thank you very much to shared

    ReplyDelete
  64. why you don't use POO??

    ReplyDelete
  65. How to delete an image ?

    ReplyDelete
  66. @Ahmad Ghallab

    User unlink($image_path);

    ReplyDelete
  67. sir how i load docs and txt file along with photo

    ReplyDelete
    Replies
    1. Modify $valid_formats = array("jpg", "png", "gif", "bmp","jpeg"); add txt extension

      Delete