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 code use jQuery ajax to upload a file to MySQLi server without page refreshing and modify HTML table to display the retrieve data on it. This is a user-friendly kind of program feel free user it in your program. 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 properties 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 run PHP scripts. Here's the link for 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. tut1

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.
  1. <?php
  2. $conn = mysqli_connect('localhost', 'root', '', 'db_upload_ajax');
  3.  
  4. if(!$conn){
  5. die("Error: Failed to connect to database!");
  6. }
  7. ?>

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.
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
  5. <link rel="stylesheet" type="text/css" href="css/bootstrap.css" />
  6. </head>
  7. <body>
  8. <nav class="navbar navbar-default">
  9. <div class="container-fluid">
  10. <a class="navbar-brand" href="https://sourcecodester.com">Sourcecodester</a>
  11. </div>
  12. </nav>
  13. <div class="col-md-3"></div>
  14. <div class="col-md-6 well">
  15. <h3 class="text-primary">PHP - Form File Upload Using Ajax</h3>
  16. <hr style="border-top:1px dotted #ccc;"/>
  17. <div class="col-md-4">
  18. <form>
  19. <input type="file" id="file" />
  20. <br />
  21. <center><button type="button" class="btn btn-primary" id="upload">Upload</button></center>
  22. <br />
  23. <div id="msg"></div>
  24. </form>
  25. </div>
  26. <div class="col-md-8">
  27. <table class="table table-bordered">
  28. <thead class="alert-info">
  29. <tr>
  30. <th>File Name</th>
  31. <th>File Path</th>
  32. </tr>
  33. </thead>
  34. <tbody id="result"></tbody>
  35. </table>
  36. </div>
  37. </div>
  38. <script src="js/jquery-3.2.1.min.js"></script>
  39. <script src="js/script.js"></script>
  40. </body>
  41. </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
  1. <?php
  2. require 'conn.php';
  3. $query = mysqli_query($conn, 'SELECT * FROM `file`');
  4. while($fetch = mysqli_fetch_array($query)){
  5. ?>
  6. <tr>
  7. <td><?php echo $fetch['filename']?></td>
  8. <td><?php echo $fetch['location']?></td>
  9. </tr>
  10. <?php
  11. }
  12. ?>
upload.php
  1. <?php
  2. require_once 'conn.php';
  3.  
  4. if(!empty($_FILES['file'])){
  5. $file_name = $_FILES['file']['name'];
  6. $file_temp = $_FILES['file']['tmp_name'];
  7. $file_size = $_FILES['file']['size'];
  8.  
  9. $exp = explode(".", $file_name);
  10. $ext = end($exp);
  11. $file = time().'.'.$ext;
  12. $location = "upload/".$file;
  13.  
  14. if($file_size < 5242880){
  15. move_uploaded_file($file_temp, $location);
  16. mysqli_query($conn, "INSERT INTO `file` VALUES('', '$file', '$location')") or die(mysqli_error());
  17. echo "success";
  18. }else{
  19. echo "error2";
  20. }
  21. }else{
  22. echo "error1";
  23. }
  24.  
  25.  
  26. ?>
script.js Note: To make the script works make sure you save this file inside the js directory.
  1. $(document).ready(function(){
  2. display_data();
  3.  
  4. function display_data(){
  5. $.ajax({
  6. url: 'data.php',
  7. type: 'POST',
  8. data: {res: 1},
  9. success: function(data){
  10. $('#result').html(data);
  11. }
  12. });
  13. }
  14.  
  15. $('#upload').on('click', function(){
  16. $(this).attr('disabled', 'disabled');
  17. var file = $('#file');
  18. var file_length = file[0].files.length;
  19. var file_data = file.prop('files')[0];
  20.  
  21. var formData = new FormData();
  22. formData.append('file', file_data);
  23. $.ajax({
  24. url: "upload.php",
  25. type: "POST",
  26. data: formData,
  27. contentType:false,
  28. cache: false,
  29. processData: false,
  30. success: function(data){
  31. if(data=="success"){
  32. $("#msg").empty();
  33. $("<center class='text-success'>Successfully uploaded!</center>").appendTo($("#msg"));
  34. $('#file').val('');
  35. display_data();
  36. }else if(data=="error1"){
  37. $("#msg").empty();
  38. $("<center class='text-danger'>Please upload file first!</center>").appendTo($("#msg"));
  39. $('#file').val('');
  40. }else if(data=="error2"){
  41. $("#msg").empty();
  42. $("<center class='text-danger'>File too large to upload!").appendTo($("#msg"));
  43. $('#file').val('');
  44. }
  45.  
  46. $('#upload').removeAttr('disabled');
  47. }
  48. });
  49. });
  50. });
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!

Add new comment