Textarea Editor With Ajax Image Upload -tinymce -froala -summernote

Contribute to this guide

guideGetting and saving data

CKEditor 5 allows you to retrieve the data from and save information technology to your server (or to your system in general) in various ways. In this guide you tin can learn about the available options forth with their pros and cons.

# Automatic integration with HTML forms

This is the classic manner of integrating the editor. Information technology is typically used in simpler CMSes, forums, comment sections, etc.

This approach is simply available in the Archetype editor and simply if the editor was used to replace a <textarea> chemical element:

            <!DOCTYPE html> <html lang="en"> <head>     <meta charset="utf-viii">     <title>CKEditor 5 - Classic editor</title>     <script src="https://cdn.ckeditor.com/ckeditor5/34.0.0/classic/ckeditor.js"></script> </caput> <body>     <h1>Classic editor</h1>     <form activeness="[URL]" method="post">         <textarea name="content" id="editor">             &lt;p&gt;This is some sample content.&lt;/p&gt;         </textarea>         <p><input type="submit" value="Submit"></p>     </form>     <script>         ClassicEditor             .create( document.querySelector( '#editor' ) )             .catch( fault => {                 console.error( error );             } );     </script> </body> </html>                      

Classic editor will automatically update the value of the <textarea> chemical element one time the user submits the class. You practise not need any boosted JavaScript code to transport the editor data to the server.

In your HTTP server, you tin can now read the editor information from the content variable of the POST request. For example, in PHP, you tin become it in this fashion:

            <?php     $editor_data = $_POST[ 'content' ]; ?>                      

Delight notation that the replaced <textarea> chemical element is updated automatically past CKEditor straight before the submission. If you need to admission the <textarea> value programatically with JavaScript (e.1000. in the onsubmit handler to validate the entered data), there is a take chances that the <textarea> element would notwithstanding store the original information. In order to update the value of the replaced <textarea>, employ the editor.updateSourceElement() method.

If you demand to get the actual data from CKEditor at any moment using JavaScript, use the editor.getData() method as described in the next section.

When y'all print the data from the database to a <textarea> chemical element in an HTML page, y'all demand to encode it correctly. For instance, if y'all use PHP and then a minimal solution would look like this:

              <?php     $data = str_replace( '&', '&amp;', $data ); ?>                

<textarea name="content" id="editor"><?= $data ?></textarea>

Thanks to that, the <textarea> will be printed out similar this:

              <textarea>&lt;p>This is some sample content.&lt;/p></textarea>

Instead of being printed like this:

              <textarea><p>This is some sample content.</p></textarea>

While simple content like mentioned higher up does not itself require to be encoded, encoding the information will prevent losing text like "<" or "<img>".

# Manually retrieving the information

When you:

  • Use Ajax requests instead of the archetype integration with HTML forms,
  • Implement a single-page application,
  • Employ a different editor blazon than the Classic editor (and hence, cannot employ the previous method),

you tin can call up the information from the editor by using the editor.getData() method.

For that, you need to store the reference to the editor because — different in CKEditor 4 — at that place is no global CKEDITOR.instances property. You can do that in multiple means, for instance by assigning the editor to a variable defined outside the and then()'s callback:

            allow editor;  ClassicEditor     .create( document.querySelector( '#editor' ) )     .then( newEditor => {         editor = newEditor;     } )     .grab( error => {         console.error( fault );     } );  // Assuming at that place is a <button id="submit">Submit</push> in your application. document.querySelector( '#submit' ).addEventListener( 'click', () => {     const editorData = editor.getData();      // ... } );                      

# Autosave feature

The Autosave feature allows you to automatically save the information (e.g. send information technology to the server) when needed (when the user inverse the content).

This plugin is unavailable in any of the builds by default then you need to install it.

Assuming that you implemented a saveData() office that sends the data to your server and returns a promise which is resolved once the data is successfully saved, configuring the autosave feature is as simple as:

            ClassicEditor     .create( document.querySelector( '#editor' ), {         plugins: [             Autosave,              // ... other plugins         ],          autosave: {             salvage( editor ) {                 return saveData( editor.getData() );             }         },          // ... other configuration options     } );                      

The autosave characteristic listens to the editor.model.certificate#change:data upshot, throttles it and executes the config.autosave.save() office.

It also listens to the native window#beforeunload result and blocks information technology in the post-obit cases:

  • The data has not been saved yet (the relieve() role did not resolve its hope or it was not called yet due to throttling).
  • Or any of the editor features registered a "pending action" (e.chiliad. that an paradigm is beingness uploaded).

This automatically secures you from the user leaving the folio earlier the content is saved or some ongoing actions similar image upload did not end.

The minimum time menstruum between two relieve deportment can exist configured using the config.waitingTime property to not overload the backend. ane second is the default waiting time before the next relieve action if zilch has changed in the meantime after the editor data has changed.

            ClassicEditor     .create( document.querySelector( '#editor' ), {         autosave: {             waitingTime: 5000, // in ms             relieve( editor ) {}         },          // ... other configuration options     } );                      

# Demo

This demo shows a simple integration of the editor with a fake HTTP server (which needs 1000ms to salvage the content).

            ClassicEditor     .create( document.querySelector( '#editor' ), {         plugins: [             Autosave,              // ... other plugins         ],          autosave: {             save( editor ) {                 return saveData( editor.getData() );             }         }     } )     .then( editor => {         window.editor = editor;          displayStatus( editor );     } )     .catch( err => {         console.error( err.stack );     } );  // Save the data to a fake HTTP server (emulated here with a setTimeout()). function saveData( data ) {     return new Hope( resolve => {         setTimeout( () => {             console.log( 'Saved', information );              resolve();         }, HTTP_SERVER_LAG );     } ); }  // Update the "Condition: Saving..." info. part displayStatus( editor ) {     const pendingActions = editor.plugins.go( 'PendingActions' );     const statusIndicator = document.querySelector( '#editor-status' );      pendingActions.on( 'modify:hasAny', ( evt, propertyName, newValue ) => {         if ( newValue ) {             statusIndicator.classList.add( 'busy' );         } else {             statusIndicator.classList.remove( 'decorated' );         }     } ); }                      

How to understand this demo:

  • The condition indicator shows when the editor has some unsaved content or pending actions.
    • If you drib a large epitome into this editor, you will see that it is busy during the entire period when the epitome is being uploaded.
    • The editor is likewise decorated when saving the content is in progress (the save()'s promise was not resolved).
  • The autosave characteristic has a throttling machinery which groups frequent changes (east.g. typing) are grouped in batches.
  • The autosave itself does non bank check whether the data has really changed. It bases on changes in the model which, in special cases, may not be "visible" in the data. You can add such a cheque yourself if y'all would like to avoid sending the same data to the server twice in a row.
  • Y'all will be asked whether you want to leave the page if an prototype is beingness uploaded or the data has non been saved successfully yet. Y'all can test that past dropping a big image into the editor or changing the "HTTP server lag" to a high value (eastward.g. 9000ms) and typing something. These deportment will make the editor "busy" for a longer time — attempt leaving the page then.

Type some text to test the autosave characteristic.

Server data:

Type some text to exam the <a href="#autosave-feature">autosave</a> feature.

# Handling users exiting the page

An additional concern when integrating the editor in your website is that the user may mistakenly exit before saving the information. This problem is automatically handled by the autosave feature described to a higher place, but if you do not use information technology and instead chose different integration methods, you should consider handling these two scenarios:

  • The user leaves the page before saving the data (e.g. mistakenly closes a tab or clicks some link).
  • The user saved the data, only there are some pending actions similar an paradigm upload.

To handle the former situation you can listen to the native window#beforeunload event. The latter state of affairs can be handled by using CKEditor 5 PendingActions plugin.

# Demo

The example beneath shows how all these mechanisms can be used together to enable or disable a "Save" button and block the user from leaving the page without saving the data.

The PendingActions plugin is unavailable in any of the builds past default so you demand to install it.

            // Note: We demand to build the editor from source. // We cannot employ existing builds in this case. import ClassicEditor from '@ckeditor/ckeditor5-editor-archetype/src/classiceditor';  import PendingActions from '@ckeditor/ckeditor5-cadre/src/pendingactions';  let isDirty = false;  ClassicEditor     .create( document.querySelector( '#editor' ), {         plugins: [             PendingActions,              // ... other plugins         ]     } )     .then( editor => {         window.editor = editor;          handleStatusChanges( editor );         handleSaveButton( editor );         handleBeforeunload( editor );     } )     .catch( err => {         console.fault( err.stack );     } );  // Handle clicking the "Relieve" button by sending the data to a // simulated HTTP server (emulated hither with setTimeout()). function handleSaveButton( editor ) {     const saveButton = document.querySelector( '#save' );     const pendingActions = editor.plugins.get( 'PendingActions' );      saveButton.addEventListener( 'click', evt => {         const data = editor.getData();          // Register the activeness of saving the data every bit a "pending action".         // All asynchronous deportment related to the editor are tracked similar this,         // and so afterwards on you only need to check `pendingActions.hasAny` to bank check         // whether the editor is busy or not.         const activity = pendingActions.add( 'Saving changes' );          evt.preventDefault();          // Save the information to a false HTTP server.         setTimeout( () => {             pendingActions.remove( action );              // Reset isDirty merely if the data did not alter in the meantime.             if ( data == editor.getData() ) {                 isDirty = false;             }              updateStatus( editor );         }, HTTP_SERVER_LAG );     } ); }  // Mind to new changes (to enable the "Save" button) and to // pending actions (to show the spinner animation when the editor is busy). function handleStatusChanges( editor ) {     editor.plugins.get( 'PendingActions' ).on( 'change:hasAny', () => updateStatus( editor ) );      editor.model.document.on( 'modify:data', () => {         isDirty = true;          updateStatus( editor );     } ); }  // If the user tries to leave the page before the data is saved, ask // them whether they are certain they want to go on. function handleBeforeunload( editor ) {     const pendingActions = editor.plugins.get( 'PendingActions' );      window.addEventListener( 'beforeunload', evt => {         if ( pendingActions.hasAny ) {             evt.preventDefault();         }     } ); }  function updateStatus( editor ) {     const saveButton = document.querySelector( '#save' );      // Disables the "Save" button when the data on the server is up to date.     if ( isDirty ) {         saveButton.classList.add( 'active' );     } else {         saveButton.classList.remove( 'active' );     }      // Shows the spinner animation.     if ( editor.plugins.become( 'PendingActions' ).hasAny ) {         saveButton.classList.add together( 'saving' );     } else {         saveButton.classList.remove( 'saving' );     } }                      

How to understand this demo:

  • The button changes to "Saving…" when the data is existence sent to the server or at that place are any other pending actions (eastward.thou. an prototype beingness uploaded).
  • Yous will be asked whether you lot want to leave the page if an prototype is beingness uploaded or the data has not been saved successfully nonetheless. Y'all can test that by dropping a big prototype into the editor or changing the "HTTP server lag" to a high value (e.thousand. 9000ms) and clicking the "Save" button. These actions volition make the editor "busy" for a longer time — try leaving the page then.

Change the content of this editor, so save it on the server.

Server data:

<p>Change the content of this editor, then relieve it on the server.</p>

slaterablat1971.blogspot.com

Source: https://ckeditor.com/docs/ckeditor5/latest/installation/advanced/saving-data.html

0 Response to "Textarea Editor With Ajax Image Upload -tinymce -froala -summernote"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel