PHP - Form File Upload Using Ajax

Submitted by: 
Language: 
Visitors have accessed this post 225 times.

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="<a href="https://sourcecodester.com">Sourcecodester</a>
  11. " rel="nofollow">https://sourcecodester.com">Sourcecodester</a>
  12. </a> </div>
  13. </nav>
  14. <div class="col-md-3"></div>
  15. <div class="col-md-6 well">
  16. <h3 class="text-primary">PHP - Form File Upload Using Ajax</h3>
  17. <hr style="border-top:1px dotted #ccc;"/>
  18. <div class="col-md-4">
  19. <form>
  20. <input type="file" id="file" />
  21. <br />
  22. <center><button type="button" class="btn btn-primary" id="upload">Upload</button></center>
  23. <br />
  24. <div id="msg"></div>
  25. </form>
  26. </div>
  27. <div class="col-md-8">
  28. <table class="table table-bordered">
  29. <thead class="alert-info">
  30. <tr>
  31. <th>File Name</th>
  32. <th>File Path</th>
  33. </tr>
  34. </thead>
  35. <tbody id="result"></tbody>
  36. </table>
  37. </div>
  38. </div>
  39. <script src="js/jquery-3.2.1.min.js"></script>
  40. <script src="js/script.js"></script>
  41. </body>
  42. </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

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.