AJAX file upload with progress bar – Javascript, PHP

In this tutorial, we are going to show you how you can upload file with AJAX. We will also be displaying a progress bar. We will be using PHP.

AJAX file upload with progress bar

There are 2 types of progress bars, one with infinite progress loop similar to this:

and one which shows the number of percentage completed like this:

We will be using the 2nd progress bar as it is more accurate than the first one.

Select file

We will be using an AJAX function to upload user selected file on the server and show the progress bar of how much the file has been uploaded. We will be creating just 2 files, 1 for client (index.php) and 1 for server (upload.php). So, start off by creating a simple HTML form in file index.php:

<form method="POST" enctype="multipart/form-data" onsubmit="return onSubmit();">
    <input type="file" name="file" id="file" />
    <input type="submit" name="submit" />
</form>
  • enctype=”multipart/form-data” and method=”POST” are important in <form> tag to upload file.

Prevent form from submitting

In order to upload file via AJAX, first we need to stop the default form action method. We can do this by return false from onsubmit attribute of <form> tag. All the code written in this tutorial is pure Javascript, there is no dependency of jQuery in this tutorial.

<script>
    function onSubmit() {
        return false;
    }
</script>

Get input type file in Javascript

Now, you have to get the user selected file and save it in a variable called file. document.getElementById(“file”) helps in getting the input type file object and it has an array of user selected files in a variable called files.

function onSubmit() {
    var file = document.getElementById("file").files[0];
    return false;
}

Call AJAX to upload file

To call an AJAX to upload the file, first create an built-in XMLHttpRequest object and save in variable ajax. This object is supported in all browsers and it is native Javascript object, no jQuery is required.

var ajax = new XMLHttpRequest();

Now call open(method, url, async) function from ajax object.

  • First parameter is the method of request GET or POST.
  • Second is the name of PHP file which will upload the file. In this case upload.php which will be created in next step.
  • Third is a boolean, whether the request is asynchronous or not. true for asynchronous. Asynchronous requests does not hang up the browser. Syncronized requests may block the browser if the script at upload.php is very time-taking.
ajax.open("POST", "upload.php", true);

Sending file via AJAX required an FormData object to be appended in the AJAX request. We can create a FormData object simply by the following line:

var formData = new FormData();
formData.append("file", file);
  • formData.append 1st parameter is the string which will used in upload.php file to upload the file and 2nd parameter is the user selected file. In this case, it is stored in variable file

Call the send() function from ajax object to actually call an AJAX request. It accepts 1 parameter that is of FormData object.

ajax.send(formData);

When response is received from server

ajax object has multiple functions that are called once the status of request is changed. For example, when server receives the request, if server does not exists, if server failed to respond etc. All these callbacks are received in a function called onreadystatechange.

ajax.onreadystatechange = function() {
    //
};

Now we have to respond only if the request is successful. In this onreadystatechange function, we have 3 variables readyState, status and responseText.

  • readyState will have value 4 when the request is done/completed.
  • status will have value 200 when everything goes right.
ajax.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
    	console.log(this.responseText);
    }
};

Save file on server – PHP

Now create a new file named upload.php and open it in code editor. In this file, we will just be storing the file in a server. Paste the following code in upload.php file:

<?php
    move_uploaded_file($_FILES["file"]["tmp_name"], $_FILES["file"]["name"]);
    echo "Done";
?>

At this point if you run the index.php file, you will be able to select a file and save it in your server and your index.php will look like this:

<form method="POST" enctype="multipart/form-data" onsubmit="return onSubmit();">
    <input type="file" name="file" id="file" />
    <input type="submit" name="submit" />
</form>

<script>
    function onSubmit() {
        var file = document.getElementById("file").files[0];

        var formData = new FormData();
        formData.append("file", file);
        
        var ajax = new XMLHttpRequest();
        ajax.open("POST", "upload.php", true);
        ajax.send(formData);

        ajax.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                console.log(this.responseText);
            }
        };

        return false;
    }
</script>

And your upload.php should look like this:

<?php
    move_uploaded_file($_FILES["file"]["tmp_name"], $_FILES["file"]["name"]);
    echo "Done";
?>

Show progress bar

Now, in order to view the progress bar you can simply create an <progress> tag anywhere in your index.php where you want to see the progress. Provide it a unique id and set it’s initial value to 0:

<progress id="progress" value="0"></progress>

Get progress bar object in javascript, right above return false; line in the function onSubmit(), like this:

function onSubmit() {
    ..........

    ajax.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            console.log(this.responseText);
        }
    };

    var progress = document.getElementById("progress");
    return false;
}

While uploading files, ajax object also has an event called onprogress that will tell the current uploaded file percentage:

ajax.upload.onprogress = function (event) {
    //
};
  • event variable will tell the current status of uploaded file.

First you have to set the maximum value of progress object to that required by an AJAX request to upload the file:

progress.max = event.total;

Now simply set the progress value attribute to uploaded value from event object:

progress.value = event.loaded;

Now, you will be able to view the progress of an uploaded file via AJAX.

Complete code

Here is a complete code of your index.php file:

<form method="POST" enctype="multipart/form-data" onsubmit="return onSubmit();">
    <input type="file" name="file" id="file" />
    <input type="submit" name="submit" />
</form>

<progress id="progress" value="0"></progress>

<script>
    function onSubmit() {
        var file = document.getElementById("file").files[0];

        var formData = new FormData();
        formData.append("file", file);
        
        var ajax = new XMLHttpRequest();
        ajax.open("POST", "upload.php", true);
        ajax.send(formData);

        ajax.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                console.log(this.responseText);
            }
        };

        var progress = document.getElementById("progress");
        ajax.upload.onprogress = function (event) {
            progress.max = event.total;
            progress.value = event.loaded;
        };

        return false;
    }
</script>

Show progress of download with remaining time – Javascript

[wpdm_package id=’104′]

Get data from database using AJAX, Javascript, PHP, MySQL

By the end of this tutorial, you will be able to get data from database using AJAX using simple Javascript (no jQuery). Benefits of using AJAX are:

  1. Page loads faster as there will be no PHP script running during page load.
  2. If you want to change data, you can do that easily without having to refresh the page.
  3. You can show the same data on multiple pages, without having to rewrite the query. Just call the same javascript function.

Where AJAX is used ?

Google Earth

When you scroll in Google Earth, an AJAX request is sent to get the images of new location.

Facebook

When you scroll at the end of page in Facebook, an AJAX request is sent to get the older posts.

Charts & Graphs

In charts, when you change the date value, the charts has been updated to selected date via AJAX.

We are going to show records of employees from database table. We are using database named classicmodel, it will be included in the source files.

Create an HTML table

First we are going to create a file to show the data from database called index.php

Create a simple HTML table and give a unique ID to <tbody> tag

<table>
    <tr>
	<th>First name</th>
	<th>Last name</th>
	<th>Job title</th>
    </tr>

    <tbody id="data"></tbody>
</table>

Call AJAX to get data from database

To call an AJAX to get the data, first create an built-in XMLHttpRequest object and save in variable ajax.

<script>
    var ajax = new XMLHttpRequest();
</script>

Now call open(method, url, async) function from ajax object.

ajax.open("GET", "data.php", true);
  • First parameter is the method of request GET or POST.
  • Second is the name of file from where to get data. In this case data.php which will be created in next step.
  • Third is a boolean, whether the request is asynchronous or not. true for asynchronous. Asynchronous requests does not hang up the browser. Syncronized requests may block the browser if the script at data.php is very time-taking.

You can also send headers with your request using the following methods:

ajax.setRequestHeader("Accept", "application/json")
ajax.setRequestHeader("Authorization", "Bearer {token}")

You can pass as many headers as you want by calling the method setRequestHeader multiple times.

Call the send() function from ajax object to actually call an AJAX request. It accepts no parameter.

ajax.send();

ajax object has multiple functions that are called once the status of request is changed. For example, when server receives the request, if server does not exists, if server failed to respond etc. All these callbacks are received in a function called onreadystatechange.

ajax.onreadystatechange = function() {
    //
};

Now we have to respond only if the request is successful. In this onreadystatechange function, we have 3 variables readyState, status and responseText.

  • readyState will have value 4 when the request is done/completed.
  • status will have value 200 when everything goes right.
ajax.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
    	console.log(this.responseText);
    }
};

Get data from MySQL database using PHP

Now create a new file named data.php and open it in code editor. First, you have to connect with database:

<?php
$conn = mysqli_connect("localhost", "root", "", "classicmodels");
  • root is the name of database user.
  • Third parameter is the password of database. For XAMPP/WAMP, it will be an empty string.
  • classicmodels is the name of database.

Now, write your query to get the records from database. In my case, I am just getting all employees from database table named employees:

$result = mysqli_query($conn, "SELECT * FROM employees");

Create an array and loop through all database records returned from previous query, and save those records in that array:

$data = array();
while ($row = mysqli_fetch_object($result))
{
    array_push($data, $row);
}

Now, whatever you echo will returned to the AJAX callback function in index.php file. In case of an array, you have to convert the array into JSON format and then echo it.

echo json_encode($data);
exit();
  1. exit(); will prevent the code from further executing.

    At this point, if you run the index.php file, you will see similar to the following in your browser console:

Now, go back to index.php file and convert this JSON string back into an array:

ajax.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
    	console.log(this.responseText);
    	var data = JSON.parse(this.responseText);
    	console.log(data);
    }
};

JSON string should now be converted into an Javascript object named data.If you run index.php now and see the browser console, you will see something similar to the following:

json-to-object

Show data in HTML table

You got the data, now you just have to append it in table. Create an empty string variable named html:

var html = "";

Loop through all employees list:

for(var a = 0; a < data.length; a++) {
    //
}

Inside the loop, append the data in html variable:

for(var a = 0; a < data.length; a++) {
    var firstName = data[a].firstName;
    var lastName = data[a].lastName;
    var jobTitle = data[a].jobTitle;

    html += "<tr>";
        html += "<td>" + firstName + "</td>";
        html += "<td>" + lastName + "</td>";
        html += "<td>" + jobTitle + "</td>";
    html += "</tr>";
}

After the loop, append the html variable in <tbody> tag:

document.getElementById("data").innerHTML += html;

Now, your index.php file should look like this:

<table>
    <tr>
	<th>First name</th>
	<th>Last name</th>
	<th>Job title</th>
    </tr>

    <tbody id="data"></tbody>
</table>

<script>
    var ajax = new XMLHttpRequest();
    ajax.open("GET", "data.php", true);
    ajax.send();

    ajax.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var data = JSON.parse(this.responseText);
            console.log(data);

            var html = "";
            for(var a = 0; a < data.length; a++) {
                var firstName = data[a].firstName;
                var lastName = data[a].lastName;
                var jobTitle = data[a].jobTitle;

                html += "<tr>";
                    html += "<td>" + firstName + "</td>";
                    html += "<td>" + lastName + "</td>";
                    html += "<td>" + jobTitle + "</td>";
                html += "</tr>";
            }
            document.getElementById("data").innerHTML += html;
        }
    };
</script>

And your data.php file should be like this:

<?php
$conn = mysqli_connect("localhost", "root", "", "classicmodels");
$result = mysqli_query($conn, "SELECT * FROM employees");

$data = array();
while ($row = mysqli_fetch_object($result))
{
    array_push($data, $row);
}

echo json_encode($data);
exit();

Run the index.php file and you will see your data will be displayed via AJAX. So that’s how you can get data from the database using AJAX and display it in an HTML table.

There is more

This is just to get the data from the database. Follow this tutorial to learn complete CRUD (Create, Read, Update and Delete) operation in AJAX.

[wpdm_package id=’93’]