Are you looking for ajax file/image upload and preview without refreshing page using Jquery. I had implemented this ajax form submitting using jquery.form plugin and used Arun Shekar's image cropping PHP code for uploading images. Just five lines of JavaScript code, Using this you can upload files, image and videos.

Download Script
Live DemoJavascript 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.
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#photoimg').live('change', function()
{
$("#preview").html('');
$("#preview").html('<img src="loader.gif" alt="Uploading...."/>');
$("#imageform").ajaxForm(
{
target: '#preview'
}).submit();
});
});
</script>
ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#photoimg').live('change', function()
{
$("#preview").html('');
$("#preview").html('<img src="loader.gif" alt="Uploading...."/>');
$("#imageform").ajaxForm(
{
target: '#preview'
}).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
?>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
Upload image <input type="file" name="photoimg" id="photoimg" />
</form>
<div id='preview'>
</div>
include('db.php');
session_start();
$session_id='1'; // User login session value
?>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
Upload image <input type="file" name="photoimg" id="photoimg" />
</form>
<div id='preview'>
</div>
Sample database design for Users.
Users
Contains user details username, password, email, profile_image and profile_image_small etc.
CREATE TABLE `users` (
`uid` int(11) AUTO_INCREMENT PRIMARY KEY,
`username` varchar(255) UNIQUE KEY,
`password` varchar(100),
`email` varchar(255) UNIQUE KEY,
`profile_image` varchar(200),
`profile_image_small` varchar(200),
)
`uid` int(11) AUTO_INCREMENT PRIMARY KEY,
`username` varchar(255) UNIQUE KEY,
`password` varchar(100),
`email` varchar(255) UNIQUE KEY,
`profile_image` varchar(200),
`profile_image_small` varchar(200),
)
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/";
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $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))
{
mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
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/";
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $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))
{
mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
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;
}
?>







Wow, this is amazing, it works! :)
Love it :)
thx..
this is what i'm looking for..
tutorial no found
http://analytics.hosting24.com/high_cpu.htmlajaximageupload/
"Live Demo" and "Download Script" links not working
Nice...!
demo link not working...
404 error on demo page !!!
nice simple script..
Problem with Hosting server overload please try after 5 min.
Soon I will move demos to Cloud hosting..
Great, I was looking for something like this and found the Uploadify, but it uses flash as a part of it. This is better than that :)
With image description how can i do ????
With image description how can i do ????
Nice script, very good.
You will have issue with this line, list($txt, $ext) = explode(".", $name);, is the file base name is with multiple dots(as in this-is-a-file.with-dot.png)
so use this to get the file extension instead:
$fileExt = substr(strrchr($fileName, '.'), 0);
Nice post.
amazing
Excellent!
I keep getting an fail error message , when ever i uploaded a picture, can't find the problem. any help appreciated.
";
}
else
echo "failed";
}
else
echo "Image file size max 2 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
?>
Great Stuff
Thank You!
Hi, thank you, I have a Question about http://www.9lessons.info/2009/06/autosuggestion-with-jquery-ajax-and-php.html
How can I do, try to select one result with keyword and the ENTER key? like Facebook I can in facebook navegate the results with the arrow of keywords
Thank You !
excellent work, thanks!
good work !
thanks !!
Yeah sehr geil vielen vielen Dank dafür ;)
Hi Srinivas,
First of all : Great script !
I was looking for such a script !
I’m implementing it on a site i’m working on, and I have just one question :
Looking at your demo pages :
How can I get the content of the var ‘$actual_image_name’ ( new filename ) displayed on the index page ( not the ajaximage.php ! ) ?
Or, in other words, how can I send the var ‘$actual_image_name’ ( new filename ) back to the index page ?
If I do an echo of the ‘$actual_image_name’ on the index page, it returns nothing ( empty )
Thank you for your quick reply !
Kind regards from the Netherlands,
Erwin van Brink
very nice post.
Onchnage is not working in IE. Please check it and update the script
IE is DEAD
Hi Srinivas, Can I post new thread on this site? - Machhindra
Hi Srinivas ( or someone else --:} ),
Could you please help me with my comment above?
I really need this to work !
Thanks !!!!
Erwin van Brink
Thank you!
Very useful for me. Thanks a lot.
thank you so much! it works in IE too :)
thank you very much Srinivas
I am Rescue, I am a complete noob, I want to be able to add the image name to a form and submit it to mysql, I dont know how, any help will be appreciated.
:)
wen i crop the image .. it is not showing what i cropped particular area..
Just want to let you know that the program I told you that i will create to translate your article in french is ready. And i will start translation each article of your website and link to the original. So each time you will post an article i will translate it in french.
You are great man. God bless you.
Thank you for these codes i selected a social network as my mini project
These tutorial is very interesting and easy to use..
Hi All,
Please help me I want to create a CMS in php with Ajax and jQuery I want a when we add and edit any content and any manager the all action are complete without page refreshing so please give me some source URL, whos help me.........
awesome
lease help me I want to create a CMS in php with Ajax and jQuery I want a when we add and edit any content and any manager the all action are complete without page refreshing so please give me some source UR
Thanks Srinivas.
will this work if i set this for multiple uploads?
Huge thx !
Do you think we can initiate o re-initiate jcrop once preview div is updated ?
Keep on posting goods articles and thx again !
nice work!
awesome
great work amazin stuffs dude really gooddd...
I've been doing ajax image upload using iframe.. It was actually a fake ajax image upload.. And now i found out that it's possible to do the ajax upload without iframe.. :D tnx men. Your the best!
very nice, congratulation.
I wold know how to make a upload like this with a lot of images and delete any of then , like this one -
http://www.ajax-image-editor.com/demo/
can you show to uss?
=)
Helo my friend, good work.
Very easy implementation code,
I wold like to know how to delete a image from server after upload , like this exemple -
http://www.fyneworks.com/jquery/multiple-file-upload/#tab-Examples
It is hard to make this?
thanks
thank you
I need a code on php to capture picture/frame of video file(flv/swf/wmv) and store it in a separate folder while uploading the video file.
I know you can help me out here.... your site is awesome.Please i need help on this.
Thanks allot sir!
I use this on linktube dot net (index).
Your credits remain in the codes
Waaaaaaaaw........amzing...it resolved my problem..thank you sooooooo much....
Hi Srinivas, if this dont work in IE, It is very hard to use, most of the users in my contrie navigates in IE, does have some way to make this work in ie?
Hi Shriniva, I did some test of your demo. It is very nice and helpful.
Thanks....
Nice article, I use this technique in my project. So, how can I upload multi file without refreshing page by using ajax?
I have a table that is generated from a mysql db and I am trying to add this code so that I can upload an image for the individual rows. So far I have it creating a new form form imageform for each row and I am wanting to name then imageForm[1] imageForm[2] and so on. I will also do the same thing with the preview divs and also the photoimg button. But I am having trouble with how to have the ajax functions recognize the arrays that I have attached to each item. Is there a way to do this?
great code thanks to u........
Dear Srinivas,
Thnx a lot for your snippet. I have used it in my general coding..it is working perfect...
But, I tried to implement it to the pages using SEO friendly URL's like http://sghss.com/works/designing/web/kishors-design-24/upload ... it won't work..
I have refereed jquery.min.js and jquery.form.js in many ways...but still showing the same error '$' is not defined..how can i escape from it ? can you help me ? thnx in advance
how can i store username or email with fileupload ?
Very very nice script
If some1 get a sol to this error put it up here, Uncaught RangeError: Maximum call stack size exceeded
If someone gets a solution to the following error; please post it here. The error is:
Uncaught RangeError: Maximum call stack size exceeded
thank you soo much man...you made my day...
Great work!!!
nice!!
but only one question!
Does form plugin works with jquerymobile??
i have tried its not working!
please help me..
@Parikshit: Please! use latest version of jQuery to solve your problem. I also fixed mine this way.
hat to u boss
Nice post dude..... :)
Help Mee
How To Make uid = ". $ _SESSION ['IdUser'];
Asalam-o-Alikum kindly help me how we can create a dymain editor e.g ckeditor,tinymse editor..but only using one texarea ...thanks regard nadia
Wow, really good script. But it would even be better if you could make it special, like under the preview image after uploading, its giving you the url, etc. domain.com/file/uploads/file.png
would be epic!
Hi,
Very Nice !!
Is it possible to call a function when submit is complete ?
Thank you
:-)
It is ok !!
$("#nameform").ajaxForm(
{target: '#preview'},
alert("Thank you for post")
).submit();
Thank you !!
Nice tutorial, image uploading successfully, but can you please tell me after form submission why new window not shown ... new window shows in the uploaded image section maybe its the iframe issue ? Thanks
Perfect :)
Nice tutorial !!!
but like i'm really curious to know why the script didn't leave index page after submit ??
Thanks !!
I keep receiving error "$("#imageform").ajaxForm is not a function". Once I select an image file to upload, the spinner starts but no image uploads or displays.
while trying demo i tried a trick!!
i have image named a.mp3.jpg
and
music file named a.jpg.mp3
when i tried to upload the image a.mp3.jpg
"Invalid file format.." message was displayed
but when i tried to upload music file a.jpg.mp3
it was successfully uploaded..............
It should not be done!
please repair your image validation script......
thank you!!!!!!!
perfect.. :)
but how can i show the image in modal box??
Hey its ver nice one but its not working in ie can you please tell me how it will work in ie i am using Input type file without textbox its working in all instead of IE.
nice script.
thank you very much
thnx bro...you are great...
not working with ie.. tested on ie9
target: '#preview' is not working either
IE FIX
change
this.appendChild( elem );
in you jqeury.js with
this.parentNode.appendChild( elem );
Thanks,it's just great and quite simple, I spend the night looking around for some other solution... Reading many time that doing this is just impossible... Your solution is the lighter and more comprehensible for me than other heavy scripts I found ... (I'm not totally noob, but I like making things working with the less code lines I can for my brain health !! ).
So thanks again, I just have two points :
Why don't you just use this code
$ext = substr($name, -3);
instead of this one :
list($txt, $ext) = explode(".", $name);
Because your authorized extensions just have 3 letters and your code doesn't manage files using several dots like this one : mynicepic.2012holidays.jpg
Second point that is more boring for me... Maybe it's a bit off the subject here, but usually I can manage it myself. I can make your code working by itself, but I didn't find a way to include it properly on my site. I mean, the form included as an include in my page doesn't point correctly an ajaximage.php and i got a 404 error. Is there a special things that I don't understand in your procedure or I'm just totally wrong about including people script ? I made this operation with a lots of scripts and form from myself or others, I've never had a 404 ! If you have few minutes to light my reflexions...
Thanks.
if you want to call a function when submit completed, use option 'success'
eg:
$("#myForm").ajaxForm(
{
success: alert("completed")
}).submit();
How to get the name of the file after submit? I can not get the result of the 'target' option to use as javascript variable. Please help me ...
my extensions here:
$valid_formats = array("jpg", "png", "gif", "bmp","mp3")
but why can't uploading mp3 file? Someone help me pls!
nice script.
thank you very much
wow
working perfect..
thank you
hi there, first this code works perfect, thanks for sharing!! :) I'm looking for some way to change another form (input text value) to catch the just saved image path, any ideas?? thanks again!
HOW TO CATCH FILE NEW PATH
Ok, here's the thing, this works fine to me:
$('#imageform').bind('submit', function(e) {
e.preventDefault(); // <-- important
$(this).ajaxSubmit({
target: '#preview',
success: function() {
$('#file').val($('#newimg').attr("src"));
}
});
}).submit();
i execute your index.php file in that time i got this error = "Opps some thing went wrong"
Instead of this: list($txt,$ext)= explode(".",$name); use this: $ext = end(explode(".",$name)); it will grab the last value in the array
Thanks for the article. It solved a very old problem. Works great in all browsers.
Realy Greattttttt!!!!!!!
I tried it but get this error:
Warning: mysql_connect() [function.mysql-connect]: [2002] No such file or directory (trying to connect via unix:///var/mysql/mysql.sock) in /Library/WebServer/Documents/temp/ajaximage/db.php on line 7
Warning: mysql_connect() [function.mysql-connect]: No such file or directory in /Library/WebServer/Documents/temp/ajaximage/db.php on line 7
Opps some thing went wrong
Can someone help please!
I have a suggestion. I think it would be better if the user name image name. as name_surname.jpg
perfect job, just perfect ! Thanks !
IE 9 Fix (works with ff,safari,chrome - did not test on opera)
$(document).ready(function() {
var options = {
target: '#preview', // target element(s) to be updated with server response
beforeSubmit: showRequest, // pre-submit callback
success: showResponse // post-submit callback
};
$('#photoimg').live('change', function () {
$('#imageform').submit(function() {
$(this).ajaxSubmit(options);
return false;
}).submit();
});
});
function showRequest(formData, jqForm, options) {
//insert animated gif loading code here
return true;
}
// post-submit callback
function showResponse(responseText, statusText, xhr, $form) {
//insert alert or whatsoever
}
can any body provide this code in java????
i have try it... nice job... but is there any way to make loader that use percentage with jquery? cheer...
@zuka Soon I'm going to publish a tut about uploading file with percentage status
if(in_array(strtolower($ext),$valid_formats))
Really nice Snippet ;)
Use "strtolower" for support file extension as ".PNG" and ".png" or something like else ...
if(in_array(strtolower($ext),$valid_formats))
Use "strtolower" for irgnoring case sensitive in file extensions.
Thanks.
thanks Srinivas Tamada,
This helps me a lot.
But i have a problem.
After image upload when i am trying to submit my parent form, it is not getting submitted.
Please help me...
Thanks in advance. :)
Hi I just started using Jquery,
I tried to implement this plugin to upload an image but the i just find the the loader repeating.
Nothing is happening, and i'm not getting any errors either
can any one help
Hi I was looking for same functionality. Alot Thanks to you!!!
Thanks! Just what I needed and it works like a charm.
how would you allow multiple file upload?
a question
how we can to post form data too ajaximage.php without action of form and with ajax
and php file need to change ?
hello can any one tel me how to delete images that are saved in upload folder??????
Thanks very much for your code. Works like a charm on my local machine. Do you need any credit for its use on the web?
Saved me loads of time, cheers.
Excellent stuff buddy, I was search for such a good implementation, thanks for sharing
Ya its working, thanks
Awesome script. thanks
thanks dear...i m searching such one.... thanks
Something weird is the script work great. but the file don't appear in the upload folder but the <img show the picture and the path is the same... after a while it's seem that the file appear but it take time. it's not the size problem because I use 100k image file.. someone know what's wrong?
W000000000000wwwwwwwwww This is Really an imaging !!!!!!!!!!!! ..
I really want to thank that person who have done that ... thank you so much sir ...
Regards: Pritam SIngh Bangalore
Thanks a lot...........
Thanks for code.
About IE onchange problem - I used jquery-1.7.min.js and changed:
$('#photoimg').live('change', function()
to
$('#photoimg').on('change', function()
Now works fine on IE9!
Many thanks for code!!