ckeditor 5, v1.11.1
I have initialised an editor as follows:
<textarea name="content" id="editor"></textarea>
<script>
ClassicEditor
.create( document.querySelector( '#editor' ) )
.then( editor => {
console.log( editor );
} )
.catch( error => {
console.error( error );
} );
</script>
I am making an ajax call (via jquery) and attempting to populate the editor with the response:
<script>
$(function() {
$.ajax({
url: '/get-editor-data',
method: 'get'
}).done(function (response) {
$('#editor').html(response.comment);
});
});
</script>
The ajax request is running successfully and returning valid JSON:
{"comment":"foo"}
So the content "foo" should appear in the editor.
But I'm getting an editor without any content in it.
If I disable ckeditor - by commenting out the first block of js (ClassicEditor...
) - so it's just a vanilla textarea the content is populated correctly.
So how do I get the content in the editor in this way?
Look at the documentation.
You have to call editor.setData(…);
.
You have editor
defined here:
.then( editor => {
… so to keep that variable in scope you need to either:
$('#editor').html(response.comment)
)then
callbackPromise.all
and get the editor and data out in the resulting array.Note, this is not a live demo because Stackoverflow's sandboxing is incompatible with CKEditor's attempt to use cookies resulting in an exception.
function init_editor() {
console.log(1);
return ClassicEditor
.create(document.querySelector("#editor"));
}
function get_data() {
console.log(2);
return $.ajax({
url: "https://cors-anywhere.herokuapp.com/https://stackoverflow.com/humans.txt",
method: "get"
});
}
$(function() {
var promises = [init_editor(), get_data()];
Promise.all(promises).then(function(results) {
results[0].setData(results[1]);
});
});