Skip to main content

PHP - Ajax Image Upload

In this tutorial we will create a Ajax Image Upload using PHP. This code will upload image file to the MySQLi database with the help of ajax request to prevent page refresh. The code use jQuery ajax to upload image file to MySQLi server by prevent the web refresh and modify HTML element properties to display the receiving data. 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

And this is the link for the jquery that i used in this tutorial

Lastly, this is the link for the bootstrap that i used for the layout design

Creating Database

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

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_ajax_image');
  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="">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 - Ajax Image Upload</h3>
  16. <hr style="border-top:1px dotted #ccc;"/>
  17. <div class="col-md-4">
  18. <form>
  19. <div class="form-group">
  20. <input type="file" id="image" class="form-control"/>
  21. </div>
  22. <br />
  23. <center><button type="button" class="btn btn-primary" id="upload">Upload</button></center>
  24. </form>
  25. </div>
  26. <div class="col-md-8" id="result" style="padding:10px; border:1px solid #000;"></div>
  27. </div>
  28. <script src="js/jquery-3.2.1.min.js"></script>
  29. <script src="js/script.js"></script>
  30. </body>
  31. </html>

Creating the Main Function

This code contains the main function of the application. This code will upload image 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

  1. <?php
  2. require_once 'conn.php';
  4. $query=mysqli_query($conn, 'SELECT * FROM `image`') or die(mysqli_error());
  5. while($fetch=mysqli_fetch_array($query)){
  6. echo "<img src='".$fetch['location']."' style='float:left; margin:15px;' width='100' height='100'/>";
  7. }
  8. ?>


  1. <?php
  2. require_once 'conn.php';
  4. if(!empty($_FILES['image'])){
  6. $image_name = $_FILES['image']['name'];
  7. $image_temp = $_FILES['image']['tmp_name'];
  8. $image_size = $_FILES['image']['size'];
  10. $exp = explode(".", $image_name);
  11. $ext = end($exp);
  12. $allowed_ext = array('jpg', 'jpeg', 'png');
  14. if(in_array($ext, $allowed_ext)){
  15. $image = time().'.'.$ext;
  16. $location = "upload/".$image;
  17. if($image_size < 5242880){
  18. move_uploaded_file($image_temp, $location);
  19. mysqli_query($conn, "INSERT INTO `image` VALUES('', '$image', '$location')") or die(mysqli_error());
  20. echo "success";
  21. }else{
  22. echo "error3";
  23. }
  24. }else{
  25. echo "error2";
  26. }
  27. }else{
  28. echo "error1";
  29. }
  31. ?>

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

  1. $(document).ready(function(){
  2. display_image();
  4. function display_image(){
  5. $.ajax({
  6. url: 'get_image.php',
  7. type: 'POST',
  8. data: {res: 1},
  9. success: function(data){
  10. $('#result').html(data);
  11. }
  12. });
  13. }
  15. $('#upload').on('click', function(){
  16. var image = $('#image');
  17. var image_data = image.prop('files')[0];
  19. var formData = new FormData();
  20. formData.append('image', image_data);
  21. $.ajax({
  22. url: "upload.php",
  23. type: "POST",
  24. data: formData,
  25. contentType:false,
  26. cache: false,
  27. processData: false,
  28. success: function(data){
  29. if(data == "success"){
  30. alert('Image Uploaded');
  31. display_image();
  32. }else if(data == "error1"){
  33. alert("Please upload file first!");
  34. }else if(data == "error2"){
  35. alert('Wrong Image format');
  36. }else if(data == "error3"){
  37. alert('File too large to upload');
  38. }
  39. }
  40. });
  41. });
  42. });

There you have it we successfully created Ajax Image Upload using PHP. 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!

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.


1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Add new comment

This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.