Jquery,Ajax file upload in PHP

There are plenty of free jquery,ajax file upload plugins are available to download from google.
But if you want to learn your own way to do this , we have written tutorials for image uploading using Jquery,Ajax in PHP.
In this tutorial we will able to upload images without page reloading .

First we have to create a HTML file to display form for uplaoding image .Find below it’s code

    <div id="upload">


Select file to upload



    <input type="file" name="fileInput" id="fileInput" />


We also require some css for stylizing the HTML form upload page. Find below css code

    border: 3px dashed #0087F7;
    border-radius: 5px;
    background: #F3F4F5;
    cursor: pointer;

    min-height: 150px;
    padding: 54px 54px;
    box-sizing: border-box;
#upload p{
    text-align: center;
    margin: 2em 0;
    font-size: 16px;
    font-weight: bold;
    display: none;

Now include jquery file to your document . You may either call using any CDN or download jquery and put inside your folder .
We are using CDN as shown below

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

Now put below js code .It will handle user browsed file then send it to upload.php to upload in server using PHP script . This file also limit user to upload maximum 1 MB size of image, Yo can change as per your requirements .

    //file input field trigger when the drop box is clicked
    //prevent browsers from opening the file when its dragged and dropped
    $(document).on('drop dragover', function (e) {

    //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
    $("#upload").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
            $("#upload").html("Please choose an images file.");
        }else if(file.size > 1048576){
            //check file size (in bytes)
            $("#upload").html("Sorry, your file is too large (>1 MB)");
            //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.onload = function () {
                //get response and show the uploading status
                var response = JSON.parse(xhr.responseText);
                if(xhr.status === 200 && response.status == 'ok'){
                    $("#upload").html("File has been uploaded successfully. Click to upload another.");
                }else if(response.status == 'type_err'){
                    $("#upload").html("Please choose an images file. Click to upload another.");
                    $("#upload").html("Some problem occured, please try again.");

Finally ,we need a php file i.e upload.php .This file first check allowed image extension then it upload to server . Below file also return response in JSON format. We can use this in html page to show any success message .

    //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';
            $response['status'] = 'err';
        $response['status'] = 'type_err';
    //render response data in JSON format
    echo json_encode($response);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s