Ajax File Upload using jQuery and PHP


In our earlier tutorial, different methods have provided to upload file in PHP. Today we’ll build a simple Ajax file upload script with jQuery and PHP. You will find many jQuery plugins for upload files or images without page refresh. But if you want to learn the Ajax file upload process and make your own Ajax file upload script, this tutorial will help you a lot.

Here we’ll show how you can upload file to the server without page refresh using jQuery, Ajax, and PHP. Using our simple Ajax file upload script, you can easily implement file upload functionality without using any 3rd party plugin.

HTML Code

The following HTML will display a file upload box. The user can select a file to upload by click on this box.

<form>      
    <div id="dropBox">
        <p>Select file to upload</p>
    </div>
    <input type="file" name="fileInput" id="fileInput" />
</form>

CSS Code

To make file upload box look good, the following CSS is used.

#dropBox{
    border: 3px dashed #0087F7;
    border-radius: 5px;
    background: #F3F4F5;
    cursor: pointer;
}
#dropBox{
    min-height: 150px;
    padding: 54px 54px;
    box-sizing: border-box;
}
#dropBox p{
    text-align: center;
    margin: 2em 0;
    font-size: 16px;
    font-weight: bold;
}
#fileInput{
    display: none;
} 

JavaScript Code

The jQuery is used in Ajax file upload script, so, the jQuery library needs to be loaded first.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

The following JavaScript code handles the file upload process and shows the upload status to the user. Also, the below script restrict the user to upload the only image file within 1 MB. Modify the file upload restrictions based on your requirement.

$(function(){
    //file input field trigger when the drop box is clicked
    $("#dropBox").click(function(){
        $("#fileInput").click();
    });
    
    //prevent browsers from opening the file when its dragged and dropped
    $(document).on('drop dragover', function (e) {
        e.preventDefault();
    });

    //call a function to handle file upload on select file
    $('input[type=file]').on('change', fileUpload);
});

function fileUpload(event){
    //notify user about the file upload status
    $("#dropBox").html(event.target.value+" uploading...");
    
    //get selected file
    files = event.target.files;
    
    //form data check the above bullet for what it is  
    var data = new FormData();                                   

    //file data is presented as an array
    for (var i = 0; i < files.length; i++) {
        var file = files[i];
        if(!file.type.match('image.*')) {              
            //check file type
            $("#dropBox").html("Please choose an images file.");
        }else if(file.size > 1048576){
            //check file size (in bytes)
            $("#dropBox").html("Sorry, your file is too large (>1 MB)");
        }else{
            //append the uploadable file to FormData object
            data.append('file', file, file.name);
            
            //create a new XMLHttpRequest
            var xhr = new XMLHttpRequest();     
            
            //post file data for upload
            xhr.open('POST', 'upload.php', true);  
            xhr.send(data);
            xhr.onload = function () {
                //get response and show the uploading status
                var response = JSON.parse(xhr.responseText);
                if(xhr.status === 200 && response.status == 'ok'){
                    $("#dropBox").html("File has been uploaded successfully. Click to upload another.");
                }else if(response.status == 'type_err'){
                    $("#dropBox").html("Please choose an images file. Click to upload another.");
                }else{
                    $("#dropBox").html("Some problem occured, please try again.");
                }
            };
        }
    }
}

Once the user selects a file, the file data is submitted to the upload.php file for uploading using PHP.

Upload File to the Server (upload.php)

Before uploading the submitted file is validated whether the file type is allowed. After successful validation file is uploaded to the server and the response data is returned as JSON format.

<?php
if(isset($_POST) == true){
    
//generate unique file name
    
$fileName time().'_'.basename($_FILES["file"]["name"]);
    
    
//file upload path
    
$targetDir "uploads/";
    
$targetFilePath $targetDir $fileName;
    
    
//allow certain file formats
    
$fileType pathinfo($targetFilePath,PATHINFO_EXTENSION);
    
$allowTypes = array('jpg','png','jpeg','gif');
    
    if(
in_array($fileType$allowTypes)){
        
//upload file to server
        
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
            
//insert file data into the database if needed
            //........
            
$response['status'] = 'ok';
        }else{
            
$response['status'] = 'err';
        }
    }else{
        
$response['status'] = 'type_err';
    }
    
    
//render response data in JSON format
    
echo json_encode($response);
}

Conclusion

We’ve tried to show the Ajax file upload process as simple as possible. You can extend our script with advanced functionality, like image preview, progress bar, etc. However, you can go through the following tutorials for different methods of file upload in PHP.

Recommended Tutorials For You

Leave a reply

CONNECT WITH CODEXWORLD