Using Rich Text Editor with Ajax

Last modified: 12-29-2014

Rich Text Editor allows users to add style to their articles (bold or italic font, underline, list item, etc). Google doc is a great example. Here we give a simple tutorial on how to integrate a Rich Text Editor into our platform, so our bloggers can write well-styled articles.

In this example, we’ll use CKEditor. It looks like this:

To setup it up, we just need:

1.Include the ckeditor script file:

<script src="//cdn.ckeditor.com/4.4.6/standard/ckeditor.js"></script>

2.Replace the textarea we have for input content with the rick editor:

Html:

...
<textarea name="content" cols=100% rows=12 id="content"></textarea>
...

Javascript:

CKEDITOR.replace('content');

Then, it should work!

Now, what we need to add is, read the content from the editor, and add content to the post data, right before the data is about to submit to the server:

$('#article-form').ajaxForm({
    ...
    beforeSubmit: function(arr, form, option){
        // arr is an array, each element 
        // is {name: ..., value: ...};
        // we set the value of field 'content' to the value 
        // read from the editor

        var contentData = CKEDITOR.instances.content.getData();
        arr.forEach(function(item){
            if(item.name == 'content')
                item.value = contentData;
        });
    },
    ...
});