Image Cropping Issue: 400 Bad Request Error with jQuery and PHP

My Question:

I’m encountering an issue with image cropping using jQuery and PHP. When attempting to crop an image and send it to the server, I consistently receive a 400 Bad Request error. I have provided a detailed description of my setup and code below.

My Description:

I’m working on a project where users can crop images before uploading them. I’m using jQuery and Croppie for client-side cropping and PHP for server-side processing. However, upon clicking the “Share Memory” button, I’m getting a 400 Bad Request error.

This is my crop.js jQuery:

$(document).ready(function(){
    $image_crop = $('#image_demo').croppie({
        enableExif: true,
        viewport: {
            width: 200,
            height: 200,
            type: 'square'
        },
        boundary: {
            width: 300,
            height: 300
        }
    });
    $('.file#post_image').on('change', function () { 
        var reader = new FileReader();
        reader.onload = function (e) {
            $image_crop.croppie('bind', {
                url: e.target.result
            }).then(function(){
                console.log('jQuery bind complete');
            });         
        }
        reader.readAsDataURL(this.files[0]);
        $('.modal#uploadimageModal').modal('show');
    });
    
    $('#share-memory').on('click', function (ev) {
        var postText = $("#post_message").val();

        $image_crop.croppie('result', {
            type: 'canvas',
            size: 'viewport'
        }).then(function (response) {
            // Create a FormData object
            const formData = new FormData();
            formData.append('post_image', response);
            formData.append('post_text', postText);
    
            // Make the fetch request
            fetch('/api/posts/memory', {
                method: 'POST',
                body: formData,
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            })
            .then(response => response.json())
            .then(data => {
                console.log('Server Response:', data);
                console.log('Post Message:', data.postText);
                console.log('Post Image:', data.response);

                // Continue with the rest of your code
            })
            .catch(error => console.error('Error:', error));

            $('.modal#uploadimageModal').modal('hide');

        });
    });
});

This is my php memory.php rest API:

<?php

${basename(__FILE__, '.php')} = function () {
    if ($this->isAuthenticated() && $this->paramsExists('post_text') && $this->paramsExists('post_image')) {
        $image_tmp = $_POST['post_image'];
        list($type, $image_tmp) = explode(';', $image_tmp);
        list(, $image_tmp) = explode(',', $image_tmp);
        $image_tmp = base64_decode($image_tmp);
        $image_tmp = md5(time());
        $text = $_POST['post_text'];
        Post::registerPost($text, $image_tmp);
    } else {
        $this->response($this->json([
            'message'=>"bad request"
        ]), 400);
    }
};

?>

This is my postregister.php:

<?php
class Post
{
    public $id;
    public $conn;

    public static function registerPost($text, $image_tmp)
    {
        if (is_file($image_tmp) and exif_imagetype($image_tmp) !== false) {
            $userid = Session::getUser()->getID();
            $author = Session::getUser()->getUsername();
            $image_name = md5($author.time()) . image_type_to_extension(exif_imagetype($image_tmp));
            $image_path = get_config('upload_path') . $image_name;
            if (file_put_contents($image_tmp, $image_path)) {
                $db = Database::getConnection();

                // Fetch the avatar value
                $avatarQuery = "SELECT `avatar` FROM `users` WHERE `owner` = '$author'";
                $avatarResult = $db->query($avatarQuery);
                $avatar = $avatarResult->fetch_assoc();
                
                $Useravatar = $avatar['avatar']; // Get the avatar value

                $image_uri = "/files/$image_name";
                $insert_command = "INSERT INTO `posts` (`userid`, `post_text`, `multiple_images`, `image_uri`, `avatar`, `like_count`, `uploaded_time`, `owner`) VALUES ('$userid', '$text', 0, '$image_uri', '$Useravatar', 0, now(), '$author')";
                // die(var_dump($insert_command));
                if ($db->query($insert_command)) {
                    $id = mysqli_insert_id($db);
                    return new Post($id);
                } else {
                    echo "<script>window.location.href="https://stackoverflow.com/Uploads?error"</script>";
                    return false;
                }
            }
        } else {
            throw new Exception("Image not uploaded check image extension. image: {$image_tmp} & Test: {$text}");
        }
    }

}
?>

Error Message:

I’m receiving the following error message in the browser console: error image here

Expected Behavior:

I expect the cropped image and associated text to be successfully sent to the server and processed without any errors.

What I’ve Tried:

  1. Checked and adjusted the client-side and server-side code as per suggestions.

  2. Verified the server endpoint and ensured it is accessible.

Environment:

  • jQuery version: 3.6.3

  • PHP version: 8.2.10

  • Croppie version: 2.6.5.

Additional Information:

I a’m using Ubuntu 23.10 and this is my problem apache2 error log click here

Leave a Comment