'Ckeditor Image Upload - Incorrect Server Repsonse

I'm having a problem uploading images. CKEditor keeps throwing an "Incorrect server response" error when using the drag and drop Upload Image addon.

I've added the following lines to my ckeditor config.js file:

config.extraPlugins = 'uploadimage';
config.imageUploadUrl = './scripts/ckImageUpload.php';
config.extraPlugins = 'image2';

And my ckImageUpload.php script is:

con = dbConnect();
$id = $_GET['edit'];
$time = new DateTime;

$fileName = $time->format(DateTime::ATOM).pathinfo($_FILES['upload']['name'], PATHINFO_EXTENSION);

$url = './images/uploaded/'.$fileName;

if(move_uploaded_file($_FILES['upload']['tmp_name'], $url)) {

    $data = ['uploaded' => 1, 'fileName' => $filename, 'url' => $url];


    $query = 'INSERT INTO postImages (
            parentID,url
        ) VALUES (
            "'.$id.'",
            "'.$url.'"
        )';

    if(!mysqli_query($con, $query)){
        $error = 'Insert query failed';
        $data = array('uploaded' => 0, 'error' => array('message' => $error));
    }

} else {

    $error = 'There was an error uploading the file';
    $data = array('uploaded' => 0, 'error' => array('message' => $error));

}

echo json_encode($data);

If I fake it and remove everything except the following lines, and place an image called image.jpg in the correct location the error goes away and the image appears within the editor as it should:

$data = ['uploaded' => 1, 'fileName' => 'image.jpg', 'url' => './images/uploaded/image.jpg'];
echo json_encode($data);


Solution 1:[1]

Instead of trusting the std. json_encode, sending an actual JSON response works.

Changing that simple

echo json_encode($data);

into:

return new Symfony\Component\HttpFoundation\JsonResponse($data);

will get this working.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 vinzee