Ajax File Upload using jQuery and PHP

HTML Code

In this tutorial, we’ll create a simple Ajax file upload script with jQuery and PHP. You will find many jQuery plugins to upload files or images without page refresh. Therefore, if you want to learn the Ajax file upload process and make your own Ajax file upload script, So our tutorial will help you a lot.

With the help of this tutorial, we will explain to you that how you can upload files to the server without refreshing the page by using jQuery, Ajax, and PHP. Using our simple Ajax file upload script, you can speedily implement file upload functionality without using any 3rd party plugin.

HTML Code

The following HTML will demonstrate 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

Use the following CSS code to make the file upload box look good.

#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

Use the jQuery in the 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 restricts the user to upload the only image file within 1 MB. Modify the file upload restrictions based on your requirements.

$(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.");
                }
            };
        }
    }
}

SEE ALSO: Distance Between Two Addresses using Google Maps API and PHP

Upload File to the Server (upload.php)

Before uploading, the submitted file is validated whether the file type is allowed. Therefore, after a successful validation file is uploaded to the server, and return the response data 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

Firstly we have tried to show the Ajax file upload process as simple as possible. Secondly, you can extend our script with advanced functionality, like image preview, progress bar, etc.

Also, read our previous blog- Radius Based Location Search with PHP and MySQL

 

Exit mobile version