1

I'm using ckeditor 4.6.2 and have come across a problem where if I change the contents in the editor, they are not being posted back to the server through an ajax call.

My set up is like this:

  • Textarea with ID #editor1 has ckeditor applied on it.
  • On page load I use ajax to load some content in to the editor from a database (this all works fine).
  • My submit button has the ID #sendBtn

I then use ajax to handle the form submission - pressing #sendBtn. The post works, but if I've edited the content in #editor1 it submits the original content - what was there on page load, not the edited content.

I came cross this post How to ajax-submit a form textarea input from CKEditor?. I've added the accepted answer before my ajax call. So my jquery for handling submission looks like this:

$('#sendBtn').click(function(e) {
    e.preventDefault();
    $('#sendBtn').prop( "disabled", true);
    var dataString = $("#emailForm").serialize();

    /**
     * https://stackoverflow.com/questions/3256510/how-to-ajax-submit-a-form-textarea-input-from-ckeditor 
     */
    for ( instance in CKEDITOR.instances )
        CKEDITOR.instances[instance].updateElement();

    $.ajax({
        url: "/admin/ajax/email",
        data: dataString,
        method: "POST",
      }).done(function(data) {
          // ...
      });
});

If I use PHP to dump the POST data at /admin/ajax/email it is showing the original content, not the updated version.

What's strange is that if I run this in my browser console, it returns true and then things appear to work:

for ( instance in CKEDITOR.instances )
    CKEDITOR.instances[instance].updateElement();

So is the issue that the above code isn't completing before the ajax call is made? How would I handle this?

Community
  • 1
  • 1
Andy
  • 5,142
  • 11
  • 58
  • 131

1 Answers1

2

OK a bit late.

As your (very helpful) reference indicates, you must update the CKEDITOR instances before you touch the form, so:

$('#sendBtn').click(function(e) {
    e.preventDefault();
    $('#sendBtn').prop( "disabled", true);

    // This before:
    for ( instance in CKEDITOR.instances )
        CKEDITOR.instances[instance].updateElement();

    // Then this:
    var dataString = $("#emailForm").serialize();

    $.ajax({
        url: "/admin/ajax/email",
        data: dataString,
        method: "POST",
      }).done(function(data) {
          // ...
      });
});
evalarezo
  • 1,134
  • 7
  • 13
  • I didn't require this code on my main form, but on another form which uses a Bootstrap modal it was the only thing that worked for me. – RossW Jun 20 '19 at 21:09