Image Upload Using Ajax In PHP | Free Source Code

Image Upload using Ajax in PHP

image upload using ajax in php

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

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.

image upload using ajax in php

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.

    $conn = mysqli_connect('localhost', 'root', '', 'db_ajax_image');
        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">
        <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
        <link rel="stylesheet" type="text/css" href="css/bootstrap.css" />	
    <nav class="navbar navbar-default">
        <div class="container-fluid">
            <a class="navbar-brand" href="">Sourcecodester</a>
    <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">
                <div class="form-group">
                    <input type="file" id="image" class="form-control"/>
                <br />
                <center><button type="button" class="btn btn-primary" id="upload">Upload</button></center>
        <div class="col-md-8" id="result" style="padding:10px; border:1px solid #000;"></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

    require_once 'conn.php';
    $query=mysqli_query($conn, 'SELECT * FROM `image`') or die(mysqli_error());
        echo "<img src='".$fetch['location']."' style='float:left; margin:15px;' width='100' height='100'/>";


    require_once 'conn.php';
        $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";
                echo "error3";
            echo "error2";
        echo "error1";

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

    function display_image(){
            url: 'get_image.php',
            type: 'POST',
            data: {res: 1},
            success: function(data){
    $('#upload').on('click', function(){
        var image = $('#image');
        var image_data = image.prop('files')[0];
        var formData = new FormData();
        formData.append('image', image_data);
            url: "upload.php",
            type: "POST",
            data: formData,
            cache: false,
            processData: false,
            success: function(data){
                if(data == "success"){
                    alert('Image Uploaded');
                }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!

Facebook Comments

Leave a Reply

Your email address will not be published. Required fields are marked *