Image Upload with Ajax, jQuery and PHP Script

You might have seen many file uploading scripts and application on web. The basic idea of file upload with ajax is uploading a file without refreshing the page or in simple words, It is method of sending or receiving data from the server without refreshing the page. We are going to give you a script which is Ajax File Uploader – using this script you can upload your file or image with the details and also see the processing percentage through progress bar. You can easily upload your image or any file by just choosing the path and your whole process is shown by the progress bar. Now moving towards the coding –

Step 1 – The HTML and Styling

This is the most important part of script. Just simply put the below HTML code in your file. File named as index.php

<!doctype html>
<html>
<head>
<title>Php And Ajax Files/Images Upload</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="styleSheet" href="style.css" type="text/css" title="The Cardindia Style">
<script src="js/jquery-3.2.1.js"></script>
<script src="js/custom.js"></script>

</head>
<body>
<div class='fileupload'>
<div class="bw-upload"> 
     <div id ="bwprv" style="height:auto; width:auto; float:left; margin-bottom: 28px; margin-left: 200px;"></div>
       </div>
    <div class="rCol" style="clear:both;">

    <label > Upload Image/file : </label> 
    <input type="file" id ="bwfile" name ='bwfile' onChange="return bw_upload_Form();">
    <input type="hidden" id="filecount" value='0'>
</div>

 <div id="progress-wrp">
 <div class="progress-bar"></div ><div class="status">0%</div>
 </div>
    <div id="output"><!-- error or success results --></div>
    </div>
</body>
</html>

After the HTML code, some styling is also important and for styling we are giving you the CSS code. You can also change the style as well.

Step 2 – The CSS

body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}  img {
width: 100px;
}  .fileupload {
width: 100%;
margin-top: 5%;
margin-left: 25%;
}  #progress-wrp {
width: 500px;
border: 1px solid #0099CC;
padding: 1px;
position: relative;
border-radius: 3px;
margin: 10px;
text-align: left;
background: #fff;
box-shadow: inset 1px 3px 6px rgba(0, 0, 0, 0.12);
display: none;
}
#progress-wrp .progress-bar{
height: 20px;
border-radius: 3px;
background-color: #3aa6bd;
width: 0;
box-shadow: inset 1px 1px 10px rgba(0, 0, 0, 0.11);
}
#progress-wrp .status{
top:3px;
left:50%;
position:absolute;
display:inline-block;
color: #000000;
}/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}

Step 3 – The PHP

This should be in upload ajax.php .

<?php 
print_r($_FILES);

if(isset($_FILES["bwfile"]["name"])){
$file = $_FILES["bwfile"];
BwFileUpload($file);
}

function  BwFileUpload($file){
if ((($file["type"] == "image/gif")
|| ($file["type"] == "image/jpeg")
|| ($file["type"] == "image/png")
|| ($file["type"] == "image/jpg"))
&& ($file["size"] < 200000000)) {

// file error check
  if ($file["error"] > 0){
    $file['error'] = $file["error"];
    } else {

    $filename =  basename( $file["name"]);



    if (file_exists("upload/" . $file["name"]))
      {
      $file['exist'] = $file["name"];
      } else {

      $newfilename = round(microtime(true))."-". $file["name"]; 
      //image name

    //echo "The file ". basename( $file["name"]). " has been uploaded.";

      move_uploaded_file($file["tmp_name"],
      "upload/" . $newfilename);
     
    }
  }
}
else
  {
  echo "Invalid file";
  }


}

?>


Step 4 – JavaScript

For JS use this code.

function bw_upload_Form() {
    var fcnt = $('#filecount').val();
    var fname = $('#filename').val();
    var imgclean = $('#bwfile');
    var imgcode = '';
    if(fcnt<=5){
    data = new FormData();
    data.append('bwfile', $('#bwfile')[0].files[0]);
      var ReaderObj = new FileReader(); // Create instance of the FileReader 
      ReaderObj.readAsDataURL($('#bwfile')[0].files[0]);
      ReaderObj.onloadend = function(){
   // set uploaded image data as background of div
   imgcode = this.result;
}
    var imgname  =  $('input[type=file]').val();
     var size  =  $('#bwfile')[0].files[0].size;

    var ext =  imgname.substr( (imgname.lastIndexOf('.') +1) );
    if(ext=='jpg' || ext=='jpeg' || ext=='png' || ext=='gif' || ext=='PNG' || ext=='JPG' || ext=='JPEG'){
     if(size<=1000000){
      $.ajax({
      url: "upload-ajax.php",
      type: "POST",
      data: data,
      enctype: 'multipart/form-data',
      processData: false,  // tell jQuery not to process the data
      contentType: false,  // tell jQuery not to set contentType
       xhr: function(){
        jQuery('#progress-wrp').show();
        //upload Progress
        var xhr = $.ajaxSettings.xhr();
        if (xhr.upload) {
            xhr.upload.addEventListener('progress', function(event) {
                var percent = 0;
                var position = event.loaded || event.position;
                var total = event.total;
                if (event.lengthComputable) {
                    percent = Math.ceil(position / total * 100);
                }
                //update progressbar
                $('#progress-wrp' +" .progress-bar").css("width", + percent +"%");
                $('#progress-wrp' + " .status").text(percent +"%");
            }, true);
        }
        return xhr;
    },
    mimeType:"multipart/form-data"
    }).done(function(data) {
      //alert(data);
      jQuery('#output').html('file uploaded Successfully');
       if(data!='FILE_SIZE_ERROR' || data!='FILE_TYPE_ERROR' ){
        fcnt = parseInt(fcnt)+1;
        $('#filecount').val(fcnt);
        var img = '<div class="dialog" id ="img_'+fcnt+'" ><img src="'+imgcode+'"><a href="#" id="rmv_'+fcnt+'" onclick="return removeit('+fcnt+')" class="close-classic"></a></div><input type="hidden" id="name_'+fcnt+'" value="'+data+'">';
        $('#bwprv').append(img);
        if(fname!=='')
        {
          fname = fname+','+data;
        }else
        {
          fname = data;
        }
         $('#filename').val(fname);
          imgclean.replaceWith( imgclean = imgclean.clone( true ) );
       }
       else
       {
         imgclean.replaceWith( imgclean = imgclean.clone( true ) );
         alert('SORRY SIZE AND TYPE ISSUE');
       }

    });
    return false;
  }//end size
  else
  {
      imgclean.replaceWith( imgclean = imgclean.clone( true ) );//Its for reset the value of file type
    alert('Sorry File size exceeding from 1 Mb');
  }
  }//end FILETYPE
  else
  {
     imgclean.replaceWith( imgclean = imgclean.clone( true ) );
    alert('Sorry Only you can uplaod JPEG|JPG|PNG|GIF file type ');
  }
  }//end filecount
  else
  {    imgclean.replaceWith( imgclean = imgclean.clone( true ) );
     alert('You Can not Upload more than 6 Photos');
  }
}




Final Words:– I hope my tutorial will help you. If you have another query related to this blog just post your comment below.


Read More –