Image Upload using AJAX

We all know that Ajax is a fastest way to create interactive web applications. We have already learned to submit a basic form through Ajax in previous blog. Today we will learn, image upload through Ajax and php as a backend language.

The form submits all the fields to a php script without page refresh, using native jQuery functions


Step 1 - Build the HTML Form:


<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
        <!-- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> -->
        <title>Ajax Image Upload</title>
    </head>
    <body>
        <div id="main" class="container">
            <h1>Upload Your Images</h1>
            <!-- Start An alert if file is uploaded -->
            <div class="alert alert-success alert-dismissible" style="display: none;">
                <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
                <strong>Success!</strong> Image Uploaded Successfully..
            </div>
            <!-- Close An alert if file is uploaded -->
            <br>
            <form enctype="multipart/form-data" id="form1">
                <div class="form-group">
                    <label for="email">Image:</label>
                    <input type="file" class="form-control" id="images" multiple name="images">
                </div>
                <div class="form-group">
                    <label for="email">Name:</label>
                    <input type="text" class="form-control" id="names" multiple name="name">
                </div>

                <button class="btn btn-default" type="submit" id="btn">Upload Files!</button>
            </form>
        </div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
        <script src="upload.js?<?= date('his') ?>"></script>
    </body>
</html>

                                


Here, we have created a basic form with ID ‘Form1’ and also included upload.js file at bottom.

Step 2 - Begin Adding jQuery:


$('#form1').submit(function (e){
    e.preventDefault(); // prevent page from reloading    
    var form = $(this);
    console.log(form);
    var form_data = new FormData(form[0]);  // same as enctype   
    console.log(form_data);
    form_data.append("add","nothing"); // isset values can be used optional
    $.ajax({
        url: "upload.php",
        type: "POST",
        data: form_data,
        processData: false,
        contentType: false,
        enctype: 'multipart/form-data',
        success: function (res) {
            console.log(res);
                if(res == 'success'){
                    $('.alert').show();
                }
        }
    });
});
                                

Here we are storing all input value in form_data variable by creating instance of FormData class.


This is output of form array. We just need 0th index of form array hence we have stored value of 0th index in form_data .


Step 3 - After this create a file to uplod image as uplod.php:

<?php
    $name = $_FILES["images"]["name"];
    move_uploaded_file( $_FILES["images"]["tmp_name"],  $_FILES['images']['name']);
    echo "success";
?>



Did you like our works?

Here is your content of the callout box lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.