Can you provide an example on how to setup CKEditor to save via AJAX using the Save button in the CKEditor toolbar?
I'm interested in creating a CKEditor AJAX save page but am not seeing any examples on their site.
Thanks!
You can use the beforeCommandExec event & cancel() method:
<script type="text/javascript">
$(document).ready(function () {
$('.ckeditoriz').ckeditor(/* config */);
$('.ckeditoriz').each(function () {
var id = $(this).attr('id'),
form = this.form;
CKEDITOR.instances[id].on('beforeCommandExec', function (event) {
if (event.data.name === 'save') {
event.cancel();
$(form).submit();
}
});
});
$('.ajaxForm').submit(function (event) {
event.preventDefault();
var $this = $(this);
$.ajax({
type: $this.attr('method'),
url: $this.attr('action'),
data: $this.serialize()
});
});
});
</script>
<form action="url" method="post" class="ajaxForm">
<!-- Your textarea must have an ID! -->
<textarea id="textarea1" name="textarea1" class="ckeditoriz"></textarea>
</form>
This doesn't work in CKEditor versions 4.0, 4.1, 4.2, however it works again since version 4.3.
Since CKEditor version 4.2 you can use the save event with the cancel() method:
CKEDITOR.instances[id].on('save', function (event) {
event.cancel();
$(form).submit();
});
Try copying straight from _source/plugins/save/plugin.js and changing as needed. Create your new plugin in /path/to/ckeditor/plugins (i.e. Not in /path/to/ckeditor/_source/plugins). For example, in /path/to/ckeditor/plugins create a new directory "AjaxSave", then in that directory create a file "plugin.js". Then in that file do something like this (adapted from the normal "save" plugin in the source folder):
(function()
{
var saveCmd =
{
modes : { wysiwyg:1, source:1 },
exec : function( editor )
{
var $form = editor.element.$.form;
if ( $form )
{
try
{
editor.updateElement();
//Here is where you put your ajax submit function. For example... if you are using
// jQuery and the ajaxform plugin, do something like this:
$($form).ajaxSubmit({
success: function(response){
//do something with the response
}
});
} catch ( e ) {
//alert(e);
}
}
}
}
var pluginName = 'ajaxsave';
CKEDITOR.plugins.add( pluginName,
{
init : function( editor )
{
var command = editor.addCommand( pluginName, saveCmd );
command.modes = { wysiwyg : !!( editor.element.$.form ) };
editor.ui.addButton( 'AjaxSave',
{
label : editor.lang.save,
command : pluginName,
icon: "/img/save.png"
});
}
});
})();
Then in the config, where you define your toolbar, change 'AjaxSave' for 'Save'.
EDIT: you must also add config.extraPlugins = "ajaxsave"; to the config.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With