Bootstrap modal close messing with cropper.js

I’m using Yii2-gallery, and am now adding crop functions with Scalar4eg/cropper. In the gallery view file there’s an edit link that when clicked opens an edit modal and populates the cropper view file via ajax. Cropping works fine right up until I close the modal and open it again. Then I get the error Uncaught imageData is undefined when I try to save the cropped image.

Modal view file that is fetched via ajax:

<?php
use yii\bootstrap\Html;
use frontend\assets\CropperAsset;

CropperAsset::register($this);
?>

<div class="crop-window" data-iid="<?= $image->id ?>">
    <?= Html::img('/uploads/update-gallery/' . $image->ownerId . '/' . $image->id . '/original.' . $image->extension, ['id' => 'edit-img']) ?>
</div>
<div class="crop-controls">
...
</div>

<?php $this->registerJs("setTimeout(function() {pictureEditInit();}, 40);", \yii\web\View::POS_READY); ?>

JS File:

function pictureEditInit() {

// Initialize cropper
var $crop = $('.crop-window > img');
$crop.cropper({
    done: function(data) {}
});
$('#save-picture-edit').click(function(e) {
    var data = $crop.cropper('getData');
    var iid = $('.crop-window').data('iid');
    $.post('/controller/save-image-crop?iid=' + iid, { data : data }, function() {
       // Refresh preview image
       ...
       // Hide crop modal
       $('#crop-modal').modal('toggle');
   });
});

The cropper is reinitialized after each ajax call. All other calls to the cropper api work, but it cannot fetch the image data after the modal close and reopen. I’m not sure how to fix this. Any advice?

Refreshing the page makes the problem disappear?

If so, there’s a problem with the JS probably caused by the way the modal works.

When you fetch the CropperAsset:: through AJAX, it will load a new JS asset which might be interfering with the already loaded asset. Not 100% sure though, since I don’t have your code.

A good test is to destroy the modal instead of hiding it in here $('#crop-modal').modal('toggle');.

1 Like

Thanks for your reply. After much testing, I’ve got it narrowed down. The $('#save-picture-edit') button is in the modal footer, and therefore not being refreshed with the ajax call. I’m still not sure what the root cause is, but I can solve this by moving that button into the ajax view file.

Great that you’ve solved!

Please give us more info if you happen to find the root cause.