Jerielle
Jerielle

Reputation: 7520

How to load a template dynamically in CKEDITOR by using ajax?

I have a database table for my saved template. All are in HTML format and I want to get a specific template using an AJAX.

Here's my code:

HTML part

<div class="form-group">
    <label>Select Template: <span class="text-info">(*Optional)</span></label>
    <select class="form-control" name="load_template" id="load-template">
        <?php if(count($templates) > 0) { ?>
        <option value="">-- load template --</option>
        <?php foreach($templates as $temp) { ?>
            <option value="<?php echo $temp['id']; ?>"><?php echo $temp['template_name']; ?></option>
        <?php } ?>
        <?php } else { ?>
            <option value="">There are no saved templates</option>
        <?php } ?>
    </select>
</div>

JS part

$('#editor').ckeditor();

$('#load-template').on('change', function(){
    var id = $(this).val();
    //do some ajax to get content...
    console.log(id);
    $.ajax({
        url: "<?php echo site_url('users/user/getLoadTemplate'); ?>",
        data: {template_id: id},
        dataType: 'html',
        type: 'post',
        beforeSend: function() {},
        success: function(template) {
            $('#editor').html(template);
            console.log(template); //ok it shows the HTML but how can I load it in my ckeditor?
        },
        error: function() {
            alert('Unable to load template. Error in AJAX');
        }
    });
});

PHP side

public function getLoadTemplate() {
    $type = $this->input->post('template_id');
    $get_template = $this->Users_model->getLoadTemplate($type);
    echo $get_template['template'];
}

How can I load my ajax response HTML in the CKEDITOR?

Upvotes: 0

Views: 1307

Answers (1)

Preethi Mano
Preethi Mano

Reputation: 445

Instead of this

$('#editor').html(template);

Try this

CKEDITOR.instances['editor'].insertHtml(template) 
                   or
CKEDITOR.instances.editor.insertHtml(template)

Upvotes: 1

Related Questions