9lessons programming blog
Loading Search
Monday, August 22, 2011

Ajax Image Upload without Refreshing Page using Jquery.

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.

Ajax Image Upload without Refreshing Page with Jquery and PHP


Download Script     Live Demo

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

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>

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

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

Share this post

Comments
{ 124 comments }
John said...

Wow, this is amazing, it works! :)

Anonymous said...

Love it :)

vandai said...

thx..
this is what i'm looking for..

Anonymous said...

tutorial no found
http://analytics.hosting24.com/high_cpu.htmlajaximageupload/

Sergi Ruiz Rodriguez said...

"Live Demo" and "Download Script" links not working

Godwin said...

Nice...!

Anonymous said...

demo link not working...

Anonymous said...

404 error on demo page !!!

Sree said...

nice simple script..

Srinivas Tamada said...

Problem with Hosting server overload please try after 5 min.

Soon I will move demos to Cloud hosting..

ajmujaa said...

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

anand selvaraj said...

With image description how can i do ????

anand selvaraj said...

With image description how can i do ????

http://www.tulliomarra.it said...

Nice script, very good.

Silas said...

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

Anonymous said...

Nice post.

Anonymous said...

amazing

Maxxs said...

Excellent!

visualupload said...

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

Anonymous said...

Great Stuff

Anonymous said...

Thank You!

§ M ® said...

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 !

Jose Aviles said...

excellent work, thanks!

Anonymous said...

good work !
thanks !!

Anonymous said...

Yeah sehr geil vielen vielen Dank dafür ;)

Anonymous said...

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

webtutor for developers said...

very nice post.

Anonymous said...

Onchnage is not working in IE. Please check it and update the script

Srinivas Tamada said...

IE is DEAD

Anonymous said...

Hi Srinivas, Can I post new thread on this site? - Machhindra

Anonymous said...

Hi Srinivas ( or someone else --:} ),

Could you please help me with my comment above?
I really need this to work !
Thanks !!!!

Erwin van Brink

Dejan said...

Thank you!

Venu said...

Very useful for me. Thanks a lot.

Anonymous said...

thank you so much! it works in IE too :)

nassimweb said...

thank you very much Srinivas

Anonymous said...

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.

Anonymous said...

:)

Anonymous said...

wen i crop the image .. it is not showing what i cropped particular area..

B and C Hosting said...

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.

TechTips said...

Thank you for these codes i selected a social network as my mini project

Saleem Mohammad said...

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

Pavan said...

awesome

BadBoy said...

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

Jagannath said...

Thanks Srinivas.

Rico Maglayon said...

will this work if i set this for multiple uploads?

Anonymous said...

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 !

Anonymous said...

nice work!

Anonymous said...

awesome

Anonymous said...

great work amazin stuffs dude really gooddd...

Site Status said...

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!

murilo santos said...

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

josh said...

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

Anonymous said...

thank you

Anonymous said...

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.

Anonymous said...

Thanks allot sir!
I use this on linktube dot net (index).

Your credits remain in the codes

Anonymous said...

Waaaaaaaaw........amzing...it resolved my problem..thank you sooooooo much....

Anonymous said...

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?

John Doe said...

Hi Shriniva, I did some test of your demo. It is very nice and helpful.

Thanks....

gps said...

Nice article, I use this technique in my project. So, how can I upload multi file without refreshing page by using ajax?

Kyle said...

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?

apstechx said...

great code thanks to u........

Kishor said...

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

Fahad said...

how can i store username or email with fileupload ?

Anonymous said...

Very very nice script

Parikshit said...

If some1 get a sol to this error put it up here, Uncaught RangeError: Maximum call stack size exceeded

Parikshit said...

If someone gets a solution to the following error; please post it here. The error is:
Uncaught RangeError: Maximum call stack size exceeded

sathish said...

thank you soo much man...you made my day...

Rajat Patel said...

Great work!!!
nice!!

but only one question!

Does form plugin works with jquerymobile??

i have tried its not working!

please help me..

Anonymous said...

@Parikshit: Please! use latest version of jQuery to solve your problem. I also fixed mine this way.

Anonymous said...

hat to u boss

zwaroop said...

Nice post dude..... :)

Deo Marvin said...

Help Mee

How To Make uid = ". $ _SESSION ['IdUser'];

nadia said...

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

Anonymous said...

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!

Anonymous said...

Hi,

Very Nice !!

Is it possible to call a function when submit is complete ?
Thank you

Anonymous said...

:-)

It is ok !!

$("#nameform").ajaxForm(
{target: '#preview'},
alert("Thank you for post")
).submit();

Thank you !!

Anonymous said...

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

Herman said...

Perfect :)

Anonymous said...

Nice tutorial !!!
but like i'm really curious to know why the script didn't leave index page after submit ??
Thanks !!

Anonymous said...

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.

Rajat Patel said...

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

fajar said...

perfect.. :)
but how can i show the image in modal box??

Anonymous said...

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.

Anonymous said...

nice script.
thank you very much

sunethsk said...

thnx bro...you are great...

Anonymous said...

not working with ie.. tested on ie9

Anonymous said...

target: '#preview' is not working either

Zeeshan Lalani said...

IE FIX
change
this.appendChild( elem );
in you jqeury.js with
this.parentNode.appendChild( elem );

Renaud Garnier said...

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.

Anonymous said...

if you want to call a function when submit completed, use option 'success'

eg:

$("#myForm").ajaxForm(
{
success: alert("completed")
}).submit();

Anonymous said...

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

Anonymous said...

my extensions here:
$valid_formats = array("jpg", "png", "gif", "bmp","mp3")
but why can't uploading mp3 file? Someone help me pls!

Kursad said...

nice script.
thank you very much

Anonymous said...

wow
working perfect..
thank you

Anonymous said...

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!

Kcho said...

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

ashique said...

i execute your index.php file in that time i got this error = "Opps some thing went wrong"

Anonymous said...

Instead of this: list($txt,$ext)= explode(".",$name); use this: $ext = end(explode(".",$name)); it will grab the last value in the array

Anonymous said...

Thanks for the article. It solved a very old problem. Works great in all browsers.

Realy Greattttttt!!!!!!!

ivoilic said...

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!

Anonymous said...

I have a suggestion. I think it would be better if the user name image name. as name_surname.jpg

Anonymous said...

perfect job, just perfect ! Thanks !

Anonymous said...

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
}

shailesh said...

can any body provide this code in java????

zuka said...

i have try it... nice job... but is there any way to make loader that use percentage with jquery? cheer...

Srinivas Tamada said...

@zuka Soon I'm going to publish a tut about uploading file with percentage status

DAGGI said...

if(in_array(strtolower($ext),$valid_formats))

Really nice Snippet ;)
Use "strtolower" for support file extension as ".PNG" and ".png" or something like else ...

DAGGI said...

if(in_array(strtolower($ext),$valid_formats))

Use "strtolower" for irgnoring case sensitive in file extensions.

Thanks.

Ashwini Agarwal said...

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

Sushil said...

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

Ashay said...

Hi I was looking for same functionality. Alot Thanks to you!!!

Admin said...

Thanks! Just what I needed and it works like a charm.

Anonymous said...

how would you allow multiple file upload?

Anonymous said...

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 ?

Anonymous said...

hello can any one tel me how to delete images that are saved in upload folder??????

Anonymous said...

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.

jose said...

Excellent stuff buddy, I was search for such a good implementation, thanks for sharing

raja said...

Ya its working, thanks

Altaf hussain said...

Awesome script. thanks

jiya said...

thanks dear...i m searching such one.... thanks

Tomy300 said...

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?

pritam singh said...

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

Anonymous said...

Thanks a lot...........

Anonymous said...

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

Post a Comment

Subscribe now!Recent Posts

Categories

Subscribe now!Popular Posts

People Says

@9lessons thank you for the great tutorials, we truly appreciate your contributions to the design community.

Smashing Magazine
After developing a site you’ll require a web hosting plan to host your site, a recommended host is justhost.com which operates a LAMP environment and has been established a number of years.

Like Me