Today I am presenting the most important social networking feature called multiple ajax image upload without refreshing the page using jquery and PHP. We just modified few lines of code in jqery.form.js plugin and renamed that to jquery.wallform.js. This feature is one of the key feature in Wall Script sale, big thanks to Arun Sekar for this code trick.
Download Script Live Demo
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 <i>prepend</i> inside <i>#preview</i> 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. 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>
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='ajaximage.php'>
Upload image:
<div id='imageloadstatus' style='display:none'><img src="loader.gif" alt="Uploading...."/></div>
<div id='imageloadbutton'>
<input type="file" name="photoimg" id="photoimg" />
</div>
</form>
Sample database design for Users.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='ajaximage.php'>
Upload image:
<div id='imageloadstatus' style='display:none'><img src="loader.gif" alt="Uploading...."/></div>
<div id='imageloadbutton'>
<input type="file" name="photoimg" id="photoimg" />
</div>
</form>
Users
Contains user details username, password and email.
CREATE TABLE `users` (
`uid` int(11) AUTO_INCREMENT PRIMARY KEY,
`username` varchar(255) UNIQUE KEY,
`password` varchar(100),
`email` varchar(255) UNIQUE KEY
)
`uid` 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)
)
`upload_id` int(11) AUTO_INCREMENT PRIMARY KEY,
`image_name` text,
`user_id_fk` int(11),
`created` int(11)
)
ajaximage.php
Contains PHP code. This script helps you to upload images into uploads folder. Image file name rename into timestamp+session_id.extention
<?php
include('db.php');
session_start();
$session_id='1'; // User session id
$path = "uploads/";
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i)
{
return "";
}
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
$ext = getExtension($name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024)) // Image size max 1 MB
{
$actual_image_name = time().$session_id.".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
//Insert upload image files names into user_uploads table
mysqli_query($db,"INSERT INTO user_uploads(image_name,user_id_fk,created) VALUES('$image_name','$session_id','$time')");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
?>
include('db.php');
session_start();
$session_id='1'; // User session id
$path = "uploads/";
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i)
{
return "";
}
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
$ext = getExtension($name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024)) // Image size max 1 MB
{
$actual_image_name = time().$session_id.".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
//Insert upload image files names into user_uploads table
mysqli_query($db,"INSERT INTO user_uploads(image_name,user_id_fk,created) VALUES('$image_name','$session_id','$time')");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
?>
db.php
Database configuration file, modify username, password and database values.
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>
Awesome Tutorial....
ReplyDeleteYou have included that in your wall script? right?
ReplyDeleteThank you for this tutorial
ReplyDeleteIt is Amazing and fast Snippet ....
ReplyDeleteNice tutorial Srinivas
ReplyDeleteThank you and I want to know how I can enter 3 Photos
ReplyDeleteThank you...
ReplyDeleteIve been looking for something like this for a while cheers
ReplyDeleteYou should't not use the functions mysql_ anymore my friend.
ReplyDeleteNice script, sorry for my english.
HELLO thank you so much for this..can you please update the tutorial. with select multiple files
ReplyDeleteselected?(mass upload)
thanks
Nice thank you for tutorial.
ReplyDeleteAwesome script
ReplyDeletei used ie6,but it don't work...
ReplyDeleteAgain Srinivas and his Hardwork both did good job.
ReplyDeletereally good code
ReplyDeletecool
ReplyDeleteFor my webs i always use Uploadify, compiled with little ajax, produce wide spectar options ex. batch upload, file limitations, alowed extensions, graphic buffer...
ReplyDeletewell, you can't select multiple files with ctrl?
ReplyDeletethanks a lot
ReplyDeleteAwesome example
ReplyDeletenice tutorial thank you
ReplyDeleteNice...... :)
ReplyDeletethank you.. Nice tutorial.
ReplyDeleteAwesome tutorial Srinivas!
ReplyDeleteSimply superb tutorial...
ReplyDeletecan you post same code using java/jsp...
ReplyDeletevery nice
ReplyDeleteDear friend,
ReplyDeleteVery nice and useful one dear brother,
Here after please use mysqli and OOP based.
Thanks..
Nice tut!
ReplyDeleteThanks for the trick Arun. keep up the good work.
ReplyDeleteGood One. But if you see in Demo page is getting reloaded.
ReplyDeletesd
ReplyDeleteYour posts are always so interesting to read, Thanks for sharing
ReplyDeletecool
ReplyDeletecooll
ReplyDeletevery nice.keep rocking
ReplyDeletevery nice
ReplyDeleteWhat about cross domains? Have you tried it?
ReplyDeletei have problem,the picture is not stable after refresh the page....please tell solution
ReplyDeletepicture is not stable after refresh the page...
ReplyDeleteVery good. Thanks
ReplyDeleteYou can try uploading more than images at a time and rearranging them by drag and drop.
ReplyDeleteVery Nice Post.
ReplyDeletethanks
Very nice Job
ReplyDeletehow's the way to make the picture could be inserted to database ?
ReplyDeletenice ....
ReplyDeleteThis script I downloaded is not working on IE but working on Google chrome.. any help please?
ReplyDeletethankx for that, i was looking for something like this.
ReplyDeletei suggest you use $( "#imageform" ).on( "onChange", function( event){
}
this is a good blog
ReplyDeleteNice!
ReplyDeletenice !
ReplyDeletegood
ReplyDeletenice bro.
ReplyDeleteThanks a lot!! I've been looking for a script like this for quite some time...
ReplyDeleteCan i love u? i know i'm a guy but this script saved me. so can i love u???
ReplyDeletevery nice...
ReplyDeletecan you please send me asp.net c# code
how to edit images and remove image?
ReplyDeleteHi, 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
ReplyDeleteGood job, the script does its job
ReplyDeleteMultiple Ajax Image Upload without Refreshing Page using Jquery.
ReplyDeleteThe Same think you can done with out JQuery. Using Php POST and set target to same location.
Very good
ReplyDeleteIn Firefox and Chrome its perfect.
ReplyDeleteIn IE I always get alert "Please select image..!" even if image is successfully uploaded.
How can I fix this?
In your older demo this does not happen http://www.9lessons.info/2011/08/ajax-image-upload-without-refreshing.html
Amazing tutorial
ReplyDeletehttp://www.9lessons.info/2013/08/multiple-ajax-image-upload-refreshing.html hi like you script but i have problem in there
ReplyDeleteit save only 1 image name in mysql i want it save multi image name in mysql field
For example if i upload 4 images so its 4 name save in my sql
can it be done if yes it will be very good
Thanks.
ReplyDeleteit helps a lot..
easy and well code..
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
ReplyDeletei uplod > 100 file of photos and get "something went wrong", what must i do ?
ReplyDeleteI have the same problem ( Anonymous, anuary 5, 2014 at 8:05 PM) :
ReplyDeleteIn Firefox and Chrome its perfect.
In IE I always get alert "Please select image..!" even if image is successfully uploaded.
How can I fix this?
getAuthorizationUrl();
ReplyDeleteheader("Location: $TwitterLoginUrl");
?>
why there class in php when in jquery we are using id preview?
ReplyDeletethanks a lot
ReplyDeleteHi, 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. Thank
ReplyDeleteThe demo only upload one image at a time in firefox
ReplyDeletethanks
ReplyDeletehow can I use this with dropzone.js?
ReplyDeleteBut there is an problem, while dragging the image's name are not showing.
ReplyDeleteUncaught TypeError: fi.fileupload is not a function I am getting this error please help me with this...
ReplyDelete