Form File Upload Using Ajax in PHP

By CampCodes Administrator

Updated on:

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

READ ALSO:   Dynamically Change Font Size Using PHP Source Code

</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!

ajax datatype file ajax file upload ajax file upload jquery ajax file upload jquery example ajax file upload mvc ajax file upload php ajax file upload progress ajax file upload progress bar jquery php ajax file upload with form data using php ajax file upload without formdata ajax files ajax form data files ajax form submit with file upload in php ajax formdata php ajax image ajax image insert update delete in mysql database using php ajax image upload ajax image upload javascript ajax image upload jquery ajax image upload jquery php example ajax image upload php script ajax image upload without refreshing page using jquery ajax multipart/form-data file upload ajax multiple image upload jquery php example ajax php multiple file upload ajax picture ajax post file ajax post file data ajax post file upload ajax send file ajax send files ajax send form data ajax send image to server ajax submit form data ajax upload file ajax upload file example ajax upload file php ajax upload image ajax upload php ajax uploader php ajaxfileupload ajaxfileupload example ajaxfileupload jquery example ajaxupload angular formdata cloudinary ajax upload codeigniter ajax file upload progress bar display image using ajax php file upload ajax file upload in php example code demo file upload through ajax file upload using ajax file upload using ajax in php form file upload using ajax formdata append file get file data in jquery hidden iframe file upload how can i send file through ajax? how do i upload a file to formdata? how to fetch image from database in php using ajax how to insert image in database using ajax in php how to send image file in ajax jquery how to upload image and save in folder in jquery how to upload image in html using jquery html file upload html file upload example javascript html5 ajax file upload image upload ajax jquery image upload using ajax php mysql insert update delete image in php with source code javascript ajax file upload javascript ajax file upload example javascript ajax upload javascript file upload example javascript formdata javascript get form data javascript post file javascript upload file ajax javascript upload file to server example javascript upload image to server jquery ajax file jquery ajax file upload jquery ajax file upload example in java jquery ajax file upload example jsp jquery ajax file upload multipart form data jquery ajax file upload tutorial jquery ajax form serialize file upload jquery ajax form submit example php jquery ajax image upload jquery ajax image upload php jquery ajax image upload with preview jquery ajax image upload without form jquery ajax post file upload jquery ajax post file upload example jquery ajax upload jquery ajax upload file jquery file upload jquery file upload ajax jquery file upload example jquery file upload php jquery fileupload jquery formdata jquery formdata append jquery image upload example jquery php file upload jquery post file upload jquery post image jquery single file upload example jquery upload file jquery upload file ajax jquery upload file example jquery upload image ajax multipart file upload javascript php ajax file upload without submit php ajax image upload php ajax image upload preview php ajax multiple file upload php code for image upload and display php file php file upload php formdata php get form data php javascript file upload php jquery file upload php tutorials react formdata send image using ajax send image using ajax jquery simple ajax file upload simple ajax file upload jquery simple ajax file upload jquery php simple ajax file upload php simple ajax upload file simple image upload using ajax in php submit form using ajax javascript typescript formdata upload and save file using javascript upload file ajax upload file php ajax upload file using ajax upload file using ajax in php example upload file using ajax php upload file using jquery ajax example upload file without submit button in php upload image ajax jquery upload image ajax jquery php mysql upload image on button click using jquery upload image on change jquery upload image php upload image to server using javascript upload image using ajax upload image using ajax in php upload image using ajax in php example upload image using ajax without form upload image using javascript ajax upload image using jquery upload image using jquery ajax upload image without using form submit in php with ajax upload pdf file using jquery ajax upload video using ajax jquery uploading both data and files in one form using ajax what are the two techniques for ajax file upload? what is form data in ajax? xhr2 file upload xmlhttprequest file upload xmlhttprequest formdata xmlhttprequest formdata file upload xmlhttprequest send xmlhttprequest upload file

Leave a Comment