Thursday, 10 August 2017

Post image without form using ajax



<!DOCTYPE html>
<html>
   <head>
      <script src="jquery.min.js"></script>
   </head>
   <body>
      <form method="post" action="upload.php" enctype="multipart/form-data">
         <input type="file" name="fileToUpload" id="fileToUpload" >
         <p class="upload-it">Upload this</p>
         <input type="submit" name="upload" value="Go" >
      </form>
      <?php
         $target_dir = "uploads/";
         $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
         $uploadOk = 1;
         $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
         // Check if image file is a actual image or fake image
         if(isset($_POST["upload"])) {
             $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
             if($check !== false) {
                 if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
                     echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
                 } else {
                     echo "Sorry, there was an error uploading your file.";
                 }
                 echo "File is an image - " . $check["mime"] . ".";
                 $uploadOk = 1;
             } else {
                 echo "File is not an image.";
                 $uploadOk = 0;
             }
         }
         ?>
      <script>
         $(function(){
             $(document).on("click", ".upload-it", function() {
                 var file_data = $("#fileToUpload").prop("files")[0];  
                 var form_data = new FormData();                 
                 form_data.append("fileToUpload", file_data);    
                 form_data.append("upload", "upload");           
                 $.ajax({
                             url: "upload.php",
                             dataType: 'script',
                             cache: false,
                             contentType: false,
                             processData: false,
                             data: form_data,                    
                             type: 'post'
                    })
             })
         })
        
      </script>
   </body>
</html>


banner
Previous Post
Next Post

0 comments: