Table of Contents
Tutorial: Image Upload using Ajax in PHP with Source Code
In this tutorial, we will create an Image Upload using Ajax in PHP. This code will upload an image file to the MySQLi database with the help of ajax request to prevent page refresh. The system uses jQuery ajax to upload an image file to the 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 that feels 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_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.
<?php $conn = mysqli_connect('localhost', 'root', '', 'db_ajax_image'); 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 - Ajax Image Upload</h3> <hr style="border-top:1px dotted #ccc;"/> <div class="col-md-4"> <form> <div class="form-group"> <input type="file" id="image" class="form-control"/> </div> <br /> <center><button type="button" class="btn btn-primary" id="upload">Upload</button></center> </form> </div> <div class="col-md-8" id="result" style="padding:10px; border:1px solid #000;"></div> </div>
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
get_image.php
<?php require_once 'conn.php'; $query=mysqli_query($conn, 'SELECT * FROM `image`') or die(mysqli_error()); while($fetch=mysqli_fetch_array($query)){ echo "<img src='".$fetch['location']."' style='float:left; margin:15px;' width='100' height='100'/>"; } ?>
upload.php
<?php require_once 'conn.php'; if(!empty($_FILES['image'])){ $image_name = $_FILES['image']['name']; $image_temp = $_FILES['image']['tmp_name']; $image_size = $_FILES['image']['size']; $exp = explode(".", $image_name); $ext = end($exp); $allowed_ext = array('jpg', 'jpeg', 'png'); if(in_array($ext, $allowed_ext)){ $image = time().'.'.$ext; $location = "upload/".$image; if($image_size < 5242880){ move_uploaded_file($image_temp, $location); mysqli_query($conn, "INSERT INTO `image` VALUES('', '$image', '$location')") or die(mysqli_error()); echo "success"; }else{ echo "error3"; } }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_image(); function display_image(){ $.ajax({ url: 'get_image.php', type: 'POST', data: {res: 1}, success: function(data){ $('#result').html(data); } }); } $('#upload').on('click', function(){ var image = $('#image'); var image_data = image.prop('files')[0]; var formData = new FormData(); formData.append('image', image_data); $.ajax({ url: "upload.php", type: "POST", data: formData, contentType:false, cache: false, processData: false, success: function(data){ if(data == "success"){ alert('Image Uploaded'); display_image(); }else if(data == "error1"){ alert("Please upload file first!"); }else if(data == "error2"){ alert('Wrong Image format'); }else if(data == "error3"){ alert('File too large to upload'); } } }); }); });
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!