PHP: how to use AJAX to upload file


We create a simple example to learn how to use AJAX to upload file.

HTML

Create simple form with a file input, we use accept attribute to validate image

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">

<html>
<head>
    <title>Tutorialspots test ajax upload</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-rc1/jquery.min.js"></script>
</head>

<body style="text-align: center;">
    <h1>Tutorialspots test upload</h1>
    <form id="form-example" action="" method="post" enctype="multipart/form-data" name="form-example">
        <div>
            <input type="file" name="image" id="image" accept="image/*" class="required" />
        </div>
         
    </form>
    <div id="result"></div>
 
</body>
</html>

Javascript:

var formData = new FormData();
$(document).ready(function(){
    
    $('#image').change(function(){
         
        formData.append('image', this.files[0]);
         
        $.ajax({
               url : 'testuploadajaxdo.php',
               type : 'POST',
               data : formData,
               processData: false,   
               contentType: false,   
               dataType: 'json',
               success : function(data) {
                   if(data.error==''){
                    $('#result').append($('<img src="'+data.image+'" />'));
                   }else alert(data.error);
               }
        }); 
        
        this.value = '';
    })
});

PHP: file testuploadajaxdo.php

<?php
if(isset($_FILES['image']) && $_FILES['image']['type'] && substr($_FILES['image']['type'],0,5)=='image'){
     
    $time = time();
    move_uploaded_file($_FILES['image']['tmp_name'],'products/'.$time.'-'.$_FILES['image']['name']);
 
    echo json_encode(array('error'=>'','image'=>"products/".$time.'-'.$_FILES['image']['name']));   
}else echo json_encode(array('error'=>'Can\'t upload image'));
?>  

We use folder products to store all uploaded images.

upload ajax

Done 😀

Demo online: Demo upload ajax

Leave a Reply