Image upload and cropped using jQuery AJAX in PHP

  • Tech Area
  • May 25, 2024



In this tutorial, We will learn how to upload image and cropped using JQuery AJAX in PHP.

Files used in this tutorial:

1- index.php (AJAX script)

2- upload.php (upload image)

Below are the step by step process of how to upload image and cropped using Jquery AJAX.

Step 1: Create index.php

In this step, create a new file index.php. This is the main file used to implement AJAX to upload and cropped image using AJAX in PHP.

index.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image Upload and Crop</title>
    <link href="https://cdn.jsdelivr.net/npm/cropperjs/dist/cropper.min.css" rel="stylesheet">
</head>
<body>
    <form id="uploadForm" enctype="multipart/form-data">
        <input type="file" name="image" id="image">
        <button type="submit">Upload Image</button>
    </form>

    <div id="cropPreview">
        <h2>Crop Preview</h2>
        <div>
            <img src="" id="croppedImage" alt="Cropped Image">
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/cropperjs"></script>
    
</body>
</html>

Now use jquery AJAX script.

<script type="text/javascript">
    $(document).ready(function(){
        var cropper;
        $('#cropPreview').hide();
        $('#image').change(function(e){
            var imageFile = e.target.files[0];
            var imageURL = URL.createObjectURL(imageFile);
            $('#cropPreview').show();
            $('#croppedImage').attr('src', imageURL);

            cropper = new Cropper($('#croppedImage')[0],{
                aspectRatio: 1/1,
                viewMode: 2
            });
        });

        $('#uploadForm').submit(function(e){
            e.preventDefault();
            var croppedCanvas = cropper.getCroppedCanvas({
                width: 300,
                height: 300
            });

            croppedCanvas.toBlob(function(blob){
                var formData = new FormData();
                formData.append('croppedImage',blob);


                $.ajax({
                    url: 'upload.php',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(response)
                    {
                        var imageurl = window.location.origin +'/ajax/img-cropped/' + response;
                        $('#croppedImage').attr('src', imageurl);
                        $('.cropper-hidden').addClass('custom-cropper-hidden');
                        $('.cropper-container').addClass('custom-cropper-container');
                    }
                });
            });
        });
    });
</script>
<style>
    .custom-cropper-hidden{
        display:block !important;
    }
    .custom-cropper-container{
        display: none !important;
    }
</style>

Step 2: Create new file for upload image

In this step, create a new file upload.php. This file used to upload cropped image into the directory.

upload.php

<?php
if(isset($_FILES["croppedImage"])){
    $target_dir = "uploads/";
    $target_file = $target_dir . uniqid() . '.png';
    $uploadOk = 1;
    
    $check = getimagesize($_FILES["croppedImage"]["tmp_name"]);
    if($check !== false) {
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }

    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    } else {
        if (move_uploaded_file($_FILES["croppedImage"]["tmp_name"], $target_file)) {
            echo $target_file;
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
}
?>

Download Source Code


Subscribe us via Email

Join 10,000+ subscriber

Subscribe on YouTube