CodeIn House

  • Laravel
  • WordPress
  • jQuery
  • Javascript
  • Contact
Home   Others   Upload Image Using Ajax Without Form in PHP using Vanilla Ja ...

Upload Image Using Ajax Without Form in PHP using Vanilla Javascript

October 1, 2020 by SNK

upload image without form using javascript with progress bar

In this tutorial, we are going to learn how to upload images using ajax without form in PHP using vanilla javascript. I will guide you through step wise step process on how to upload the image file using pure javascript and not mixed with any jquery or any other.

We are just going to use pure javascript. We are also going to have a progress bar to check if the image has been successfully uploaded.

As bootstrap makes it easy to develop a form without having to keep much effort. I will use bootstrap 4 CDN and integrate it into this sample project to quickly create the form to get started.

Let’s get started and develop features that can upload images using ajax without form.

Create the file structure as shown in the image below:-

upload_image_using_ajax

How to Upload Image Using Ajax Without Form

What are we going to do?

  1. Prepare Elegant HTML form quickly and easily using bootstrap.
  2. Uploading an image with javascript with Ajax and PHP.

Making the design Ready

index.php

index.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" />      
<div class="container mt-5">
    <div class="offset-2 col-md-6">
        <div class="card">
            <div class="card-header">File Upload Example With Progressbar - CodeInHouse.com</div>
            <div class="card-body">
                <div class="custom-file">
                    <input type="file" name="image_file" class="custom-file-input" id="customFile" onchange="onSetFilename(this)">
                    <label class="custom-file-label" id="custom-file-label" for="customFile">Choose file</label>
                </div>
                <div class="progress mt-3">
                    <div id="progressBar" class="progress-bar progress-bar-striped bg-success" role="progressbar" style="width: 0%" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100"></div>
                </div>
                <button type="button" onclick="uploadFile()" class="btn btn-warning text-white mt-2">Upload File</button>
            </div>
        </div>
    </div>
</div>

Uploading an image with javascript with Ajax and PHP.

Add the javascript functions to update the selected image file into the selected box and Ajax code to make requests to the server and send over the image asynchronously.

index.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<script>
    function onSetFilename(data) {
        let fileName = data.value.split("\\").pop();
        document.getElementById("custom-file-label").innerText=fileName;
        document.getElementById("progressBar").style.width="0%";
        document.getElementById("progressBar").classList.add("bg-success");
    }
 
    function uploadFile() {
        const image_files = document.getElementById('customFile').files;
        if(image_files.length) {
            let formData = new FormData();
            formData.append('image', image_files[0]);
            let xhr = new XMLHttpRequest();
            xhr.open("POST", 'upload.php', true);
            xhr.addEventListener("progress", function (e) {
                if(e.lengthComputable) {
                    let percentComplete = e.loaded / e.total * 100;
                    document.getElementById("progressBar").style.width=percentComplete + '%';
                }
            }, false);
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    const data = JSON.parse(this.responseText);
                    if(data.success === 1) {
                        document.getElementById("progressBar").classList.remove("bg-success");
                        document.getElementById("progressBar").classList.add("bg-danger");
                        alert("Image Uploading failed. Try again..")
                    }
                }
            };
            xhr.send(formData);
        } else {
            alert("No image selected");
        }  
    }
</script>

As we have sent our image file into the server now, we have to write some code in PHP to grab the image file process and upload it to our server.

upload.php

upload.php
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
function uploadImage($array_name, $imageName, $path)
{
    if (move_uploaded_file($_FILES[$array_name]['tmp_name'], $path . $imageName))
    {
        echo json_encode(['success' => 1]);
        return (true);
    }
    else
    {
        echo json_encode(['success' => 0]);
        return (false);
    }
}
if ($_FILES['image']['name'] != '')
{
    $image = $_FILES['image']['name'];
    uploadImage('image', $image, 'images/');
}

Finally, your file will be uploaded into your root directory inside the /image folder. If you have any other problem regarding uploading images without using form submit in PHP with ajax you can contact us via the contact form on our website. Glad to help.

SHARE ON
Buffer

Enjoyed this article?

Like us on

Others

Avatar for SNK

About SNK

Hello Welcome to my Blog. I develop Websites Using Laravel Framwork & WordPress. Get Latest updates on Facebook | Twitter

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Get Connected !! With Us

TOP POSTS

  • How to Setup Spring MVC Project From Scratch in Intellij IDEA ?
  • Spring Configuration Class in JAVA [Class VS XML Config]
  • Annotations Based Configuration in Spring Framework
  • How to Configure Spring Framework with XML Configurations?
  • How to Remove Project Name from URL in JSP Project in Intellij IDEA ?

TUTORIALS TILL DATE

  • September 2022 (6)
  • June 2021 (7)
  • October 2020 (5)
  • September 2020 (6)
  • September 2018 (14)
  • August 2018 (3)
  • July 2018 (4)
  • March 2018 (8)
  • February 2018 (5)
  • January 2018 (1)
  • December 2017 (2)
  • August 2017 (8)
  • May 2017 (1)
  • April 2017 (1)
  • March 2017 (4)
  • February 2017 (3)
  • January 2017 (4)

CATEGORIES

  • Angular (2)
  • CSS3 (3)
  • D3 (3)
  • HTML5 (7)
  • JAVA (11)
  • Javascript (20)
  • jQuery (8)
  • Laravel (35)
  • Others (3)
  • PHP (11)
  • Spring (2)
  • WordPress (10)

Top Categories

  • Angular
  • CSS3
  • D3
  • HTML5
  • JAVA
  • Javascript
  • jQuery
  • Laravel
  • Others
  • PHP
  • Spring
  • WordPress

Get in Touch

DMCA.com Protection Status

Recent Articles

  • How to Setup Spring MVC Project From Scratch in Intellij IDEA ?
  • Spring Configuration Class in JAVA [Class VS XML Config]
  • Annotations Based Configuration in Spring Framework
  • How to Configure Spring Framework with XML Configurations?
  • How to Remove Project Name from URL in JSP Project in Intellij IDEA ?

© 2012-22 CodeIn House.  •  All Rights Reserved.