Ajax Select and Upload Multiple Images with Jquery
Wall Script
Wall Script
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;
}
web notification

101 comments:

  1. Replies
    1. but how to remove selected images ...? in case of i dont want some images .what i do??

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

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

    ReplyDelete
  3. 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
  4. Please develop a ranking system for points

    ReplyDelete
  5. 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
  6. box.com limit download.
    You can upload mediafire.com

    ReplyDelete
  7. Nice Lakshmi maddukuri thanks Srinivas tamada

    ReplyDelete
  8. @Ahmad Rasheed Which country you from?

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

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

    ReplyDelete
  11. 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
  12. 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
  13. Great article but dont work in IE :(

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

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

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

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

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

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

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

    ReplyDelete
  21. This script is beautiful! Worked perfect

    ReplyDelete
  22. 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
  23. Nice.. What about the same but with backbone, underscore and java?

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

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

    ReplyDelete
  26. 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
  27. 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
  28. 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
  29. Thanks for the tutorial !! I really like all your scripts !!

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

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

    ReplyDelete
  32. @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
  33. I don't want to move files before submit form, but i still want to preview. How to do it?

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

    Thank you!

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

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

    ReplyDelete
  37. 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
  38. Great code............

    ReplyDelete
  39. 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
  40. 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
  41. 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
  42. works fine but its only store 1 image to mysql table...

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

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

    ReplyDelete
  45. 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
  46. That really worked with mysql php just as i wanted ... thanx a ton :D

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

    ReplyDelete
  48. Thanks for your support !!

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

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

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

    ReplyDelete
  52. thanks dude.you done a good job

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

    B

    ReplyDelete
  54. 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
  55. 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
  56. hi this is kumar...when i upload file in localhost it is showing something went wrong pop up can u please help me

    ReplyDelete
  57. 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
  58. This is very nice tutorial Do you have any Codeigniter related with this process

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

    ReplyDelete
  60. 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
    Replies
    1. I had the same issue. what i did to fix this issue is change localhost to 127.0.0.1 then it worked.

      Delete
  61. 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
  62. I don't want to move files before submit form, but i still want to preview. How to do it?

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

    ReplyDelete
  64. nice tutorial ...

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

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

    ReplyDelete
  66. How to delete an image ?

    ReplyDelete
  67. @Ahmad Ghallab

    User unlink($image_path);

    ReplyDelete
  68. 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
  69. how to upload multiple image into mysql table in single row

    ReplyDelete
  70. Very Nice thanks for sharing this with us.

    ReplyDelete
  71. i want to upload image using mobile , show error message " Aw, snap!
    Something went wrong while displaying this webpage
     if you're seeing this frequently, try these suggestions"

    desktop version working fine
    http://www.9lessons.info/2013/09/multiple-ajax-image-upload-jquery.html

    Please check on mobile

    ReplyDelete
  72. Very impressive and unique, I enjoyed it

    ReplyDelete

mailxengine Youtueb channel
Make in India
X