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">
        <meta charset="UTF-8" />
        <link rel="stylesheet" href="">
        <!-- <script src=""></script> -->
        <title>Ajax Image Upload</title>
        <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..
            <!-- Close An alert if file is uploaded -->
            <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 class="form-group">
                    <label for="email">Name:</label>
                    <input type="text" class="form-control" id="names" multiple name="name">

                <button class="btn btn-default" type="submit" id="btn">Upload Files!</button>
        <script src=""></script>
        <script src="upload.js?<?= date('his') ?>"></script>


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);
    var form_data = new FormData(form[0]);  // same as enctype   
    form_data.append("add","nothing"); // isset values can be used optional
        url: "upload.php",
        type: "POST",
        data: form_data,
        processData: false,
        contentType: false,
        enctype: 'multipart/form-data',
        success: function (res) {
                if(res == 'success'){

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:

    $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.