Form File Upload Using Ajax in PHP

July 1, 2020
PHP
form file upload using ajax

In this tutorial, we will create a Form File Upload using Ajax. This code will upload a file to the MySQLi database without refreshing the browser after submission. The system uses jQuery ajax to upload a file to the MySQLi server without page refreshing and modify the HTML table to display the retrieve data on it. This is a user-friendly kind of program feel free to the user in your application.

We will be using jQuery, a JavaScript framework that design to simplify HTML DOM tree traversal and manipulation. It can retrieve DOM and manipulate each property of an element based on different criteria such as id, class, etc.

Getting Started:

First, you have to download & install XAMPP or any local server that runs PHP scripts. Here’s the link for the XAMPP server https://www.apachefriends.org/index.html.

And this is the link for the jquery that I used in this tutorial https://jquery.com/.

Lastly, this is the link for the bootstrap that I used for the layout design https://getbootstrap.com/.

Creating Database

Open your database web server, then create a database name in it db_upload_ajax; after that, click Import, then locate the database file inside the folder of the application then click ok.

form file upload using ajax

Creating the database connection

Open your any kind of text editor(notepad++, etc..). Then just copy/paste the code below then name it conn.php.

<?php
    $conn = mysqli_connect('localhost', 'root', '', 'db_upload_ajax');
 
    if(!$conn){
        die("Error: Failed to connect to database!");
    }
?>

Creating The Interface

This is where we will create a simple form for our application. To create the forms simply copy and write it into your text editor, then save it as index.php.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
        <link rel="stylesheet" type="text/css" href="css/bootstrap.css" />
    </head>
<body>
    <nav class="navbar navbar-default">
        <div class="container-fluid">
            <a class="navbar-brand" href="https://sourcecodester.com">Sourcecodester</a>
        </div>
    </nav>
    <div class="col-md-3"></div>
    <div class="col-md-6 well">
        <h3 class="text-primary">PHP - Form File Upload Using Ajax</h3>
        <hr style="border-top:1px dotted #ccc;"/>
        <div class="col-md-4">
            <form>
                <input type="file" id="file" />
                <br />
                <center><button type="button" class="btn btn-primary" id="upload">Upload</button></center>
                <br />
                <div id="msg"></div>
            </form>
        </div>
        <div class="col-md-8">
            <table class="table table-bordered">
                <thead class="alert-info">
                    <tr>
                        <th>File Name</th>
                        <th>File Path</th>
                    </tr>
                </thead>
                <tbody id="result"></tbody>
            </table>
        </div>
    </div>

http://js/jquery-3.2.1.min.js

http://js/script.js

</body>
</html>

Creating the Main Function

This code contains the main function of the application. This code will upload a file when the button is clicked. To make this just copy and write these block of codes below inside the text editor, then save it as shown below
data.php

<?php
    require 'conn.php';
    $query = mysqli_query($conn, 'SELECT * FROM `file`');
    while($fetch = mysqli_fetch_array($query)){
?>
<tr>
    <td><?php echo $fetch['filename']?></td>
    <td><?php echo $fetch['location']?></td>
</tr>
<?php
    }
?>

upload.php

<?php
    require_once 'conn.php';
 
    if(!empty($_FILES['file'])){
        $file_name = $_FILES['file']['name'];
        $file_temp = $_FILES['file']['tmp_name'];
        $file_size = $_FILES['file']['size'];
 
        $exp = explode(".", $file_name);
        $ext = end($exp);
        $file = time().'.'.$ext;
        $location = "upload/".$file;
 
        if($file_size < 5242880){
            move_uploaded_file($file_temp, $location);
            mysqli_query($conn, "INSERT INTO `file` VALUES('', '$file', '$location')") or die(mysqli_error());
            echo "success";
        }else{
            echo "error2";
        }
    }else{
        echo "error1";
    }
 
 
?>

script.js
Note: To make the script works make sure you save this file inside the js directory.

$(document).ready(function(){
    display_data();
 
    function display_data(){
        $.ajax({
            url: 'data.php',
            type: 'POST',
            data: {res: 1},
            success: function(data){
                $('#result').html(data);
            }
        });
    }
 
    $('#upload').on('click', function(){
        $(this).attr('disabled', 'disabled');
        var file = $('#file');
        var file_length = file[0].files.length;
        var file_data = file.prop('files')[0];
 
        var formData = new FormData();
        formData.append('file', file_data);
        $.ajax({
            url: "upload.php",
            type: "POST",
            data: formData,
            contentType:false,
            cache: false,
            processData: false,
            success: function(data){
                if(data=="success"){
                    $("#msg").empty();
                    $("<center class='text-success'>Successfully uploaded!</center>").appendTo($("#msg"));
                    $('#file').val('');
                    display_data();
                }else if(data=="error1"){
                    $("#msg").empty();
                    $("<center class='text-danger'>Please upload file first!</center>").appendTo($("#msg"));
                    $('#file').val('');
                }else if(data=="error2"){
                    $("#msg").empty();
                    $("<center class='text-danger'>File too large to upload!").appendTo($("#msg"));
                    $('#file').val('');
                }
 
                $('#upload').removeAttr('disabled');
            }
        });
    });
});

There you have it we successfully created Form File Upload using Ajax. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!

https://www.campcodes.com/

This is a free education portal. You can use every source code in your project without asking permission to the author. Share our website to everyone to make our community of programmers grow more.

    , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

    Leave a Reply

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