Ajax Image Upload and Preview | Lessoncup Programming Blog

Saturday, 28 December 2013

Ajax Image Upload and Preview

Hi, today i am going to tell you about how to upload a image using jquery and ajax, in jquery we don't have direct option to send files data to database or move to folders like regular form data, for that we need use jquery form plugin, this plugin provide you ajaxFrom and ajaxSubmit options with that we can easily send the files data along with regular data, i have done this using jquery form plugin, let's see how we do this


JAVASCRIPT

here download the jquery.form.js plugin from jquery site, and include in you file along with regular jquery plugin, now write the click function to .btn as a selector inside the function you can use ajaxSubmit() or ajaxFrom(), i used ajaxSubmit()  method to form ID name #imageuploadFrom, this method will submit the form via AJAX in the both methods have some options we can use like URL, TYPE, TARGET, DATA, DATATYPE, REPLACE TARGET  i will give you more details about ajaxFrom ajaxSubmit in coming lessons, well here inside the ajaxSubmit method i just used target option to give the server response which is coming from imageupload.php file 
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>

<script type="text/javascript" src="jquery.form.js"></script>

<script>

$(document).ready(function(){
 
 
 $('.btn').click(function(){
  
  $('#preview').fadeIn(400).html('<img src="loader.gif" align="absmiddle">&nbsp;<span class="loading">sending</span>');
  
  $("#imageuploadFrom").ajaxSubmit({
   
   target: '#preview'
      
  });
  
  $('#imageuploadFrom').clearForm()
  
  
 })


});

</script>

HTML

in html just take a form and give it ID name #imageuploadForm and give the file name in action attribute action="imgupload.php", inside the form take a file input box and one button input. next take one DIV and give it ID name #preview to display the response from imageupload.php file
<div class="lessoncup">
<div id="loader"></div>
<form action="imgupload.php" method="post" enctype="multipart/form-data" id="imageuploadForm">

<input name="image" type="file" class="image"><br/>

<input type="button" value="UPLOAD" id="btn" class="btn">

</form>

<div id="preview"></div>

</div>

PHP

here use the $_FILES concept to access the files data and store it in one variable, now we are going to allowing those files only which is related to IMAGE, for that take an array and keep the image formats in array('jpg','jpeg','png','gif'); 

now use explode() method to separate the format form file name and store it in one variable, now it is time to match the uploaded file format to multiple array file formats, use in_array() method inside the if condition to match the multiple array data
<?php
extract($_REQUEST);
include('db.php');

$file = $_FILES['image']['name'];

$img_format=array('jpg','jpeg','png','gif');

$get_format=explode('.',$file);

list($name, $ext) = $get_format;

if(!$file){
 
 echo '<div class="msg">no file chosen</div>';
 
}else if(in_array($ext,$img_format)) {
 
 move_uploaded_file($_FILES['image']['tmp_name'],"images/".$file);
 
 $sql=mysql_query("insert into images(img) values($file)");
 
 echo "<img src='images/".$file."' class='img'>";

}else{
  
echo '<div class="msg">image format must be jpg, jpeg, png, gif</div>';
 
}

?>

Live Demo   Download Script

17 comments :

  1. This comment has been removed by the author.

    ReplyDelete
  2. bro but after refresh or closing the browser the image disappears can u do like that after refresh or closing browser or computer when ever i will open the page image display ??

    ReplyDelete
  3. or can u plzz help me in this code ....


    ";
    }



    if(isset($_POST["submit"]))
    {

    $fn=$_FILES["file"]["name"];

    $res = move_uploaded_file($_FILES["file"]["tmp_name"],"photos/".$fn);
    $file = "photos/".$fn;
    echo($file);
    header("location:form.php");

    }
    ?>

    it display the image after refresh but its making loop when i upload the file like abc.jpg if i upload the xyz.jpg it display both old abc.jpg and xyz.jpg... i want to delete the old one automatically after new upload ....

    ReplyDelete
  4. HI
    Can you pls explain me script of php for upload files and it's also download throw download link which is show on webpage.

    pls send me code on my mail id jobmailsumit@gmail.com or
    Facebook id sumit.cinco@gmail.com

    ReplyDelete
  5. Please make some video tutorials on youtube

    ReplyDelete
  6. how to increment to multiple files?

    ReplyDelete
  7. how to display the uploaded image without clicking on upload button?

    ReplyDelete
  8. Using explode('.',$file); is bad in practice.

    It ll works fine for that files whose name don't have dot(".") in it.

    Like 23333.jpg, aaaa.png etc.


    But if the image name like this :

    123.aa.jpg

    This file name is valid but image cant be uploaded because according to explode it returns type "aa.jpg" not "jpg".


    ReplyDelete
  9. Use HTML5 upload api for file uploading. Not use jquery

    Check this link : http://tutorialaction.com/html5_file_upload_with_prograss_bar

    ReplyDelete
  10. This comment has been removed by the author.

    ReplyDelete

Mohammad Khasim
Blogger | Web Developer
Hyderabad - INDIA
lessoncup@gmail.com

PHP | My SQL | JQUERY
Web Development Tools | CMS | Frameworks | SEO

Get my Latest Lessons