Easy Ajax Image Upload with jQuery, PHP | Coding Cage

Easy Ajax Image Upload with jQuery, PHP

By
In this tutorial we have a simple script which will Upload an Image using jQuery Ajax with PHP, we have simple file uploading tutorial on this blog but how about using ajax, it is very simple to upload an image to the server via jQuery ajax() without refreshing the whole page, once an image was uploaded it will be viewed on the same page. PHP code was used at the back-end which will select and upload an image and the uploading process will be done by ajax() method, let's see ajax php image upload example.
Easy Ajax Image Upload with jQuery, PHP without Page Refresh
 

there are only 3 files we need for this tutorial, simple HTML form to accept valid image file, php file to upload selected image to the server side and javascript code to upload image easily without reloading page and to view the uploaded file into the particular div.

index.php

simple file contains only html form to accept image file to upload and send the request to the PHP file called "ajaxupload.php" via ajax() method.

<!doctype html>
<html>
<head lang="en">
 <meta charset="utf-8">
 <title>Easy Ajax Image Upload with jQuery and PHP - codingcage.com</title>
    <link rel="stylesheet" href="style.css" type="text/css" />
 <script type="text/javascript" src="js/jquery-1.11.3-jquery.min.js"></script>
 <script type="text/javascript" src="js/script.js"></script>
</head>
<body>
<div class="container">
 <h1><a href="">Easy Ajax Image Upload with jQuery</a></h1>
 <hr> 
 <div id="preview"><img src="no-image.jpg" /></div>
    
 <form id="form" action="ajaxupload.php" method="post" enctype="multipart/form-data">
  <input id="uploadImage" type="file" accept="image/*" name="image" />
  <input id="button" type="submit" value="Upload">
 </form>
    <div id="err"></div>
 <hr>
 <p><a href="http://www.codingcage.com" target="_blank">www.codingcage.com</a></p>
</div>
</body>
</html>

ajaxupload.php

this file contains only PHP code which will upload an image to the directory "uploads/" via ajax, here i have given the validation for the image and it will upload only valid extension images.
<?php

$valid_extensions = array('jpeg', 'jpg', 'png', 'gif', 'bmp'); // valid extensions
$path = 'uploads/'; // upload directory

if(isset($_FILES['image']))
{
 $img = $_FILES['image']['name'];
 $tmp = $_FILES['image']['tmp_name'];
  
 // get uploaded file's extension
 $ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));
 
 // can upload same image using rand function
 $final_image = rand(1000,1000000).$img;
 
 // check's valid format
 if(in_array($ext, $valid_extensions)) 
 {     
  $path = $path.strtolower($final_image); 
   
  if(move_uploaded_file($tmp,$path)) 
  {
   echo "<img src='$path' />";
  }
 } 
 else 
 {
  echo 'invalid file';
 }
}

?>






script.js

Simple jQuery/JavaScript code to upload and view image without page refresh. using $.ajax() method an image file wil be send to the "ajaxupload.php" file and file will be uploaded and viewed at the same time.
$(document).ready(function (e) {
 $("#form").on('submit',(function(e) {
  e.preventDefault();
  $.ajax({
         url: "ajaxupload.php",
   type: "POST",
   data:  new FormData(this),
   contentType: false,
         cache: false,
   processData:false,
   beforeSend : function()
   {
    //$("#preview").fadeOut();
    $("#err").fadeOut();
   },
   success: function(data)
      {
    if(data=='invalid file')
    {
     // invalid file format.
     $("#err").html("Invalid File !").fadeIn();
    }
    else
    {
     // view uploaded file.
     $("#preview").html(data).fadeIn();
     $("#form")[0].reset(); 
    }
      },
     error: function(e) 
      {
    $("#err").html(e).fadeIn();
      }          
    });
 }));
});

that's it, how it becomes easy to upload an image to the server via ajax code, feel free to contact me regarding this tutorial, hope you like it.



35 comments:

  1. A script for popup login in php with mysql please. Help will be appreciated

    ReplyDelete
    Replies
    1. Hello Himanshu, i will post login/signup popup tutorial soon ...

      Delete
    2. i have got one. Will give as a code of thanks please tell me how could i send it to you??

      Delete
    3. Hi Himanshu, you can mail me ...

      Delete
  2. Hello ! Is it possible to have same script with insert record in Mysql Database ?

    ReplyDelete
    Replies
    1. CETMOI DENIS, yes, it is possible.

      Put the SQL instructions right after the "echo" on the script

      if(move_uploaded_file($tmp,$path))
      {
      echo "your image";
      //Here goes your sql instructions - if the image is successfully uploaded to the folder, //you should be able to insert data on mysql
      }

      Hope it helps!

      Delete
  3. Thank you for sharing the information.It is very interesting blog on PHP

    ReplyDelete
    Replies
    1. Hello Ramya... thanks for visiting :)

      Delete
  4. thanks for the tutorials, I learned a lot

    ReplyDelete
    Replies
    1. you're welcome, jose, keep visiting :)

      Delete
  5. Thanks for sharing great information in your blog. Got to learn new things from your Blog . It was very nice blog to learn about php

    ReplyDelete
  6. Amazing tutorial, Can't thank you enough!

    ReplyDelete
  7. Thanks for sharing great information

    ReplyDelete
  8. How do I preview the image before I upload it?

    ReplyDelete
  9. this php script is really nice and awesome and it is really it is best blog thanks

    php Training in Chennai

    ReplyDelete
  10. Hi, Pradeep, thanks for sharing this code..
    I use this code to update image file.. it's working... but when I implemented this code to update image file to database, it only sent null to image coloum... how to fix it?

    ReplyDelete
  11. I always like to reference tutorials like this. Really well done~

    --
    Sam Smith
    Technology Evangelist and Aspiring Chef
    Large file transfers made easy.
    www.innorix.com/en/DS

    ReplyDelete
  12. Thaks for sharing the nice tutorial.

    ReplyDelete
  13. Hello ! Is it possible to have same script with insert record in Mysql Database ?

    ReplyDelete
  14. Good Job on this post. Thank you for taking the time to help others.
    THANK YOU...!!!

    ReplyDelete
  15. Wow gracias por el post esta calidad lo he mejorado haber como hago para subirlo y compartir de igual que ustedes...!!

    ReplyDelete
  16. Thank u very much for great image upload script...using ajax

    ReplyDelete
  17. What if I have 7 different inputs how do I store it in the database? Please help thanks.

    ReplyDelete
  18. What if I had 7 different image inputs how do I store the BLOB in database? Please help me I'm kinda stuck in my current situation. Thanks.

    ReplyDelete
  19. Pretty article! I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing.
    Regards,

    PHP Training in Chennai | Webdesigning Training in Chennai

    ReplyDelete
  20. Thank yoou for posting useful post.Request to visit

    Best dotnet training in chennai

    ReplyDelete
  21. I love your work! It is simple,
    yet effective. You have inspired me to create organized worksheets just like yours.
    Your students are lucky to have you! Thanks for all the freebies!...best regards....best regards.

    sap hana online training

    ReplyDelete
  22. Wonderful guide. This is really informative and effective post. Thanks for the shearing and keep update more.
    Internet Marketing Courses in Chennai

    ReplyDelete