PHP: how to use AJAX to upload file

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


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

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

    <title>Tutorialspots test ajax upload</title>
    <script src=""></script>

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


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

PHP: file testuploadajaxdo.php

if(isset($_FILES['image']) && $_FILES['image']['type'] && substr($_FILES['image']['type'],0,5)=='image'){
    $time = time();
    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

Related Post

, , , , ,

No comments yet.

Leave a Reply