Tuesday, February 11, 2014

Select And Upload Multiple Images With jQuery & Ajax

HII Guyz my name is Husain Saify Welcome To hunklessons. In this lessons i am going to teach you guyz how to upload images without refreshing the page. For this we are using jQuery and jQuery form plugin it has a Just few lines of JavaScript code, Using this you can upload files, image and videos without refreshing the page.
Select And Upload Multiple Images With jQuery & Ajax
Select And Upload Multiple Images With jQuery & Ajax

Download Script View Demo 

index.php

in index.php there is some jQuery code that perform ajax request to the server and prepend the uploaded image to the View div. In plain english we can say that every time the INPUT FILE TAG is change we are submitting the form to upload.php using ajaxForm Method.
<html>
<head>
 <title>jQuery & Ajax Multiple Image Upload</title>
 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
 <script type="text/javascript" src="./js/jquery.form.js"></script>
</head>
<body>
 <div id="view" style="height:auto"></div>
 <form action="upload.php" method="post" enctype="multipart/form-data" id="imgform">
  Upload Image:
  <div id="imageloader" style="display:none;"><img src="https://fbstatic-a.akamaihd.net/rsrc.php/v2/yb/r/GsNJNwuI-UM.gif" style="height:20px;"></div>
  <div id="imagebutton"><input type="file" name="file"/></div>
 </form>
 <script type="text/javascript">
 $('#imgform').on('change',function(){ //submit the form when image is selected
  $('#imgform').ajaxForm({target: '#view',
   beforeSend: function(){//show the loader
    $('#imageloader').show();
    $('#imagebutton').hide();
   },success: function(){ //show the file button
    $('#imageloader').hide();
    $('#imagebutton').show();
   },error: function() {
    $('#imageloader').hide();
    $('#imagebutton').show();
   }
  }).submit();
 });
 </script>
</body>
</html>

upload.php

upload.php is a simple php page. this page simply check that the image file is valid or not. if the file is valid then it upload it to the server by using move_uploaded_file() function in php
';
<?php
function getExt($name){
 $str = strtolower($name);
 $data = explode(".", $str);
 $n = count($data) -1;
 return $data[$n];
}
 if(isset($_FILES['file'])){
  $name = $_FILES['file']['name'];
  $size = $_FILES['file']['size'];
  $tmp = $_FILES['file']['tmp_name'];
  $ext = getExt($name);
  $valideFormat = array('jpg','png','gif');
  //if file is had a valid format
  if(in_array($ext, $valideFormat)){
   //if size is fine
   if($size < 220833){
    //upload the file
    $newname = time().".".$ext;
    if(move_uploaded_file($tmp, './upload/'.$newname)){
    echo '<img src="./upload/'.$newname.'" style="width:250px;margin:5px;">';
    }
   }else{
    echo "Size more than 200kbs";
   }
  }else{
   echo "Invalid Format. Select a jpg png or gif image";
  }
 }

?>