How to Image Upload Using Ajax in PHP

Mar 12, 2022 . Admin



Hello dev,

I am going to explain you Ajax image upload with Ajax with Jquery and PHP. You will learn how to PHP Ajax image upload with Ajax. In side this article we will see how to PHP upload Image with Ajax Using Jquery

This article will give you simple example of Ajax image upload with jquery in PHP. We will use get simple upload image in AJAX PHP .

I will give you simple Example how to image upload in Jquery AJAX PHP so follow this and learn Image Upload Using Ajax .

So, let's see bellow solution:

index.php
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <title></title>
    <style>
        .input-design{
            border: 1px solid #ccc;
            padding: 3px;
            border-radius: 5px;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="card mt-5">
        <div class="card-header">
            <h3>How to Image Upload Using Ajax in PHP Example</h3>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-8">
                    <form id="file-form" method="post">
                        <div class="form-group">
                            <label for="exampleFormControlFile1">Example File Input</label>
                            <input type="file" name="file" class="form-control-file input-design" id="file">
                            <span id="error" class="text-danger"></span><br>
                            <input type="submit" class="btn btn-primary btn-sm mt-2">
                        </div>
                    </form>
                </div>
                <div class="col-md-4" id="img">
                    <img src="" class="img-thumbnail" id="show-img" height="200px" width="300px">
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
    $(document).ready(function(){
        $("input").prop('required',true);
        $('#file').change(function () {
            var ext = this.value.match(/\.(.+)$/)[1];
                switch (ext) {
                    case 'jpg':
                    case 'jpeg':
                    case 'png':
                        $('#uploadButton').attr('disabled', false);
                        $('#error').text("");
                        break;
                    default:
                        $('#error').text("File Must Be Of Type jpeg,jpg,png");
                        this.value = '';
                }
        });

        $('#file').change(function () {
            const file = this.files[0]; 
            if (file){
                let reader = new FileReader();
                reader.onload = function(event){    
                    $('#show-img').attr('src', event.target.result);
                }
              reader.readAsDataURL(file);
            }
        });

        $('#file-form').on('submit',(function(e) {

            e.preventDefault();

            var fd = new FormData();
            var files = $('#file')[0].files[0];
            fd.append('file',files);

            $.ajax({
                type:'POST',
                url: 'insert_form_data.php',
                data:fd,
                cache:false,
                contentType: false,
                processData: false,
                success:function(data){
                    $('#show-img').attr('src','image/'+data);
                    alert("Image Upload successfully");
                    $('#file').val("");
                    $('#show-img').attr('src',"");
                },
            });
        }));
    });
</script>

</body>
</html>
insert_form_data.php


<?php 

    $conn = mysqli_connect('localhost','root','root','image');

    if($conn == true){

        $filename = $_FILES['file']['name'];
        @$file_name = $_FILES['file']['name'];
        @$file_size = $_FILES['file']['size'];
        @$file_tmp = $_FILES['file']['tmp_name'];
        @$file_type = $_FILES['file']['type'];
        @$file_ext=strtolower(end(explode('.',$file_name)));
        move_uploaded_file($file_tmp,"image/".$file_name);
        echo $filename; 

        $query = "INSERT INTO uplode_image(image) VALUES ('$filename')";
        $result = mysqli_query($conn,$query);

    }
?>

Output:

It will help you...
#PHP