Search code examples
javascriptsummernote

Multiple Summernote instances - upload images to server


So I'm using the summernote editor with symfony forms and I managed to upload my images to server without saving them in base64 format. Another problem comes, I have two summernote editors and when I upload image in the second one, it's inserted in the first one. I tried to use jQuery's each() loop but It didn't work out. The problem is in the upload function, It's working fine without it but I need to upload my images to the server. Here's my code:

$(document).ready(function () {
        $('.editor').summernote({
            callbacks: {
                onImageUpload: function (files) {
                    sendFile(files[0]);
                }
            }
        });

function sendFile(img) {
    var formData = new FormData();
    formData.append("img", img);
    $.ajax({
        data: formData,
        type: "POST",
        url: "/admin/upload-editor",
        cache: false,
        contentType: false,
        processData: false,
        success: function (url) {
            $('.editor').summernote('insertImage', url);
        }
    });
}
});

Solution

  • EDIT: My previous loop logic was wrong so I passed a key to iterate over each editor.

    $(document).ready(function () {
        $('.editor').each(function (i) {
                $('.editor').eq(i).summernote({
                    callbacks: {
                        onImageUpload: function (files) {
                            sendFile(files[0], i);
                        }
                    }
                });
            }
        );
    
        function sendFile(img, i) {
            var formData = new FormData();
            formData.append("img", img);
            $.ajax({
                data: formData,
                type: "POST",
                url: "/admin/upload-editor",
                cache: false,
                contentType: false,
                processData: false,
                success: function (url) {
                    $('.editor').eq(i).summernote('insertImage', url);
                }
            });
        }
    });