Multiple Ajax Image Upload without Refreshing Page using Jquery.
Wall Script
Follow Me:
Tuesday, August 06, 2013

Multiple Ajax Image Upload without Refreshing Page using Jquery.

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.

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


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.

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.

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
)

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)
)

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;
}
?>

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);
?>
Was this article helpful?
Thanks! Your feedback helps us to improve 9lessons.info


78 comments:

  1. You have included that in your wall script? right?

    ReplyDelete
  2. Thank you for this tutorial

    ReplyDelete
  3. It is Amazing and fast Snippet ....

    ReplyDelete
  4. Thank you and I want to know how I can enter 3 Photos

    ReplyDelete
  5. Ive been looking for something like this for a while cheers

    ReplyDelete
  6. You should't not use the functions mysql_ anymore my friend.

    Nice script, sorry for my english.

    ReplyDelete
  7. HELLO thank you so much for this..can you please update the tutorial. with select multiple files
    selected?(mass upload)

    thanks

    ReplyDelete
  8. Again Srinivas and his Hardwork both did good job.

    ReplyDelete
  9. For my webs i always use Uploadify, compiled with little ajax, produce wide spectar options ex. batch upload, file limitations, alowed extensions, graphic buffer...

    ReplyDelete
  10. well, you can't select multiple files with ctrl?

    ReplyDelete
  11. thank you.. Nice tutorial.

    ReplyDelete
  12. can you post same code using java/jsp...

    ReplyDelete
  13. Dear friend,

    Very nice and useful one dear brother,
    Here after please use mysqli and OOP based.

    Thanks..

    ReplyDelete
  14. Thanks for the trick Arun. keep up the good work.

    ReplyDelete
  15. Good One. But if you see in Demo page is getting reloaded.

    ReplyDelete
  16. Nice tut. could you keep another tutorial to upload more than 1 photos at a time.

    ReplyDelete
  17. Your posts are always so interesting to read, Thanks for sharing

    ReplyDelete
  18. What about cross domains? Have you tried it?

    ReplyDelete
  19. i have problem,the picture is not stable after refresh the page....please tell solution

    ReplyDelete
  20. picture is not stable after refresh the page...

    ReplyDelete
  21. You can try uploading more than images at a time and rearranging them by drag and drop.

    ReplyDelete
  22. Very Nice Post.
    thanks

    ReplyDelete
  23. how's the way to make the picture could be inserted to database ?

    ReplyDelete
  24. This script I downloaded is not working on IE but working on Google chrome.. any help please?

    ReplyDelete
  25. thankx for that, i was looking for something like this.

    i suggest you use $( "#imageform" ).on( "onChange", function( event){

    }

    ReplyDelete
  26. Thanks a lot!! I've been looking for a script like this for quite some time...

    ReplyDelete
  27. Can i love u? i know i'm a guy but this script saved me. so can i love u???

    ReplyDelete
  28. very nice...
    can you please send me asp.net c# code

    ReplyDelete
  29. how to edit images and remove image?

    ReplyDelete
  30. 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
  31. Good job, the script does its job

    ReplyDelete
  32. Multiple Ajax Image Upload without Refreshing Page using Jquery.

    The Same think you can done with out JQuery. Using Php POST and set target to same location.

    ReplyDelete
  33. In 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?
    In your older demo this does not happen http://www.9lessons.info/2011/08/ajax-image-upload-without-refreshing.html

    ReplyDelete
  34. http://www.9lessons.info/2013/08/multiple-ajax-image-upload-refreshing.html hi like you script but i have problem in there
    it 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

    ReplyDelete
  35. Thanks.
    it helps a lot..
    easy and well code..

    ReplyDelete
  36. 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
  37. i uplod > 100 file of photos and get "something went wrong", what must i do ?

    ReplyDelete
  38. I have the same problem ( Anonymous, anuary 5, 2014 at 8:05 PM) :

    In 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?

    ReplyDelete
  39. getAuthorizationUrl();
    header("Location: $TwitterLoginUrl");
    ?>

    ReplyDelete
  40. why there class in php when in jquery we are using id preview?

    ReplyDelete
  41. 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. Thank

    ReplyDelete
  42. The demo only upload one image at a time in firefox

    ReplyDelete
  43. how can I use this with dropzone.js?

    ReplyDelete
  44. But there is an problem, while dragging the image's name are not showing.

    ReplyDelete
  45. Uncaught TypeError: fi.fileupload is not a function I am getting this error please help me with this...

    ReplyDelete

Make in India