! Missing { Inserted.
Getting and saving data
CKEditor five allows yous to retrieve the data from and save it to your server (or to your system in general) in various means. In this guide you can learn most the available options along with their pros and cons.
# Automated integration with HTML forms
This is the classic manner of integrating the editor. It is typically used in simpler CMSes, forums, comment sections, etc.
This arroyo is only available in the Classic editor and simply if the editor was used to supplant a <textarea> element:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-eight"> <championship>CKEditor 5 - Archetype editor</title> <script src="https://cdn.ckeditor.com/ckeditor5/33.0.0/classic/ckeditor.js"></script> </head> <torso> <h1>Archetype editor</h1> <form action="[URL]" method="post"> <textarea name="content" id="editor"> <p>This is some sample content.</p> </textarea> <p><input type="submit" value="Submit"></p> </grade> <script> ClassicEditor .create( document.querySelector( '#editor' ) ) .catch( error => { console.fault( error ); } ); </script> </body> </html> Archetype editor volition automatically update the value of the <textarea> element once the user submits the form. You do not need any boosted JavaScript code to send the editor data to the server.
In your HTTP server, you can now read the editor information from the content variable of the POST request. For instance, in PHP, you tin can become it in this way:
<?php $editor_data = $_POST[ 'content' ]; ?> Please note that the replaced <textarea> element is updated automatically by CKEditor straight before the submission. If y'all need to access the <textarea> value programatically with JavaScript (e.chiliad. in the onsubmit handler to validate the entered information), there is a run a risk that the <textarea> element would even so store the original data. In society to update the value of the replaced <textarea>, use the editor.updateSourceElement() method.
If yous need to get the actual data from CKEditor at whatsoever moment using JavaScript, use the editor.getData() method as described in the side by side section.
When you lot print the data from the database to a <textarea> element in an HTML folio, you need to encode information technology correctly. For instance, if you utilize PHP so a minimal solution would expect like this:
<?php $information = str_replace( '&', '&', $data ); ?> <textarea proper name="content" id="editor"><?= $data ?></textarea>
Thanks to that, the <textarea> will be printed out similar this:
<textarea><p>This is some sample content.</p></textarea>
Instead of being printed like this:
<textarea><p>This is some sample content.</p></textarea>
While elementary content like mentioned above does non itself require to be encoded, encoding the data volition preclude losing text like "<" or "<img>".
# Manually retrieving the data
When you:
- Use Ajax requests instead of the classic integration with HTML forms,
- Implement a unmarried-folio awarding,
- Use a different editor type than the Archetype editor (and hence, cannot use the previous method),
yous can retrieve the data from the editor by using the editor.getData() method.
For that, you lot need to shop the reference to the editor because — unlike in CKEditor 4 — there is no global CKEDITOR.instances property. Y'all tin practice that in multiple ways, for example by assigning the editor to a variable defined outside the then()'southward callback:
permit editor; ClassicEditor .create( document.querySelector( '#editor' ) ) .then( newEditor => { editor = newEditor; } ) .catch( error => { console.error( error ); } ); // Bold there is a <push button id="submit">Submit</button> in your application. certificate.querySelector( '#submit' ).addEventListener( 'click', () => { const editorData = editor.getData(); // ... } ); # Autosave characteristic
The Autosave characteristic allows you to automatically salvage the information (due east.yard. send information technology to the server) when needed (when the user changed the content).
This plugin is unavailable in any of the builds by default so you need to install it.
Assuming that you lot implemented a saveData() role 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 equally simple as:
ClassicEditor .create( document.querySelector( '#editor' ), { plugins: [ Autosave, // ... other plugins ], autosave: { save( editor ) { return saveData( editor.getData() ); } }, // ... other configuration options } ); The autosave feature listens to the editor.model.document#alter:data result, throttles information technology and executes the config.autosave.relieve() role.
It also listens to the native window#beforeunload event and blocks information technology in the following cases:
- The data has not been saved yet (the
relieve()function did non resolve its hope or it was not chosen yet due to throttling). - Or any of the editor features registered a "pending action" (e.g. that an prototype is being uploaded).
This automatically secures you from the user leaving the folio before the content is saved or some ongoing deportment like image upload did not terminate.
The minimum time flow betwixt ii save actions can be configured using the config.waitingTime property to not overload the backend. 1 second is the default waiting fourth dimension earlier the next save action if nothing has changed in the meantime after the editor data has changed.
ClassicEditor .create( certificate.querySelector( '#editor' ), { autosave: { waitingTime: 5000, // in ms relieve( editor ) {} }, // ... other configuration options } ); # Demo
This demo shows a simple integration of the editor with a faux HTTP server (which needs 1000ms to save the content).
ClassicEditor .create( document.querySelector( '#editor' ), { plugins: [ Autosave, // ... other plugins ], autosave: { salvage( editor ) { render saveData( editor.getData() ); } } } ) .and then( editor => { window.editor = editor; displayStatus( editor ); } ) .catch( err => { console.fault( err.stack ); } ); // Save the information to a false HTTP server (emulated here with a setTimeout()). function saveData( information ) { render new Promise( resolve => { setTimeout( () => { console.log( 'Saved', information ); resolve(); }, HTTP_SERVER_LAG ); } ); } // Update the "Status: Saving..." info. part displayStatus( editor ) { const pendingActions = editor.plugins.get( 'PendingActions' ); const statusIndicator = document.querySelector( '#editor-status' ); pendingActions.on( 'change:hasAny', ( evt, propertyName, newValue ) => { if ( newValue ) { statusIndicator.classList.add together( 'busy' ); } else { statusIndicator.classList.remove( 'busy' ); } } ); } How to understand this demo:
- The condition indicator shows when the editor has some unsaved content or pending actions.
- If you drop a big image into this editor, you will see that it is busy during the entire catamenia when the prototype is being uploaded.
- The editor is also busy when saving the content is in progress (the
save()'s promise was not resolved).
- The autosave feature has a throttling mechanism which groups frequent changes (e.g. typing) are grouped in batches.
- The autosave itself does not bank check whether the data has really inverse. It bases on changes in the model which, in special cases, may not be "visible" in the data. You can add such a check yourself if you would like to avoid sending the same data to the server twice in a row.
- Yous will exist asked whether you want to go out the page if an image is being uploaded or the data has non been saved successfully yet. You tin test that by dropping a big image into the editor or irresolute the "HTTP server lag" to a high value (e.thousand. 9000ms) and typing something. These actions will make the editor "decorated" for a longer fourth dimension — try leaving the page then.
Blazon some text to test the autosave feature.
Server information:
Blazon some text to test the <a href="#autosave-feature">autosave</a> feature.
# Treatment users exiting the page
An additional business organisation when integrating the editor in your website is that the user may mistakenly leave before saving the data. This problem is automatically handled by the autosave characteristic described to a higher place, but if you do not use information technology and instead chose dissimilar integration methods, you should consider treatment these two scenarios:
- The user leaves the page earlier saving the information (e.g. mistakenly closes a tab or clicks some link).
- The user saved the information, but in that location are some pending actions similar an paradigm upload.
To handle the quondam situation you lot tin can listen to the native window#beforeunload issue. The latter situation can be handled by using CKEditor 5 PendingActions plugin.
# Demo
The case below shows how all these mechanisms can be used together to enable or disable a "Save" push and cake the user from leaving the folio without saving the data.
The PendingActions plugin is unavailable in whatever of the builds by default then yous need to install information technology.
// Notation: Nosotros need to build the editor from source. // We cannot use existing builds in this instance. import ClassicEditor from '@ckeditor/ckeditor5-editor-classic/src/classiceditor'; import PendingActions from '@ckeditor/ckeditor5-core/src/pendingactions'; permit isDirty = fake; ClassicEditor .create( document.querySelector( '#editor' ), { plugins: [ PendingActions, // ... other plugins ] } ) .so( editor => { window.editor = editor; handleStatusChanges( editor ); handleSaveButton( editor ); handleBeforeunload( editor ); } ) .take hold of( err => { console.error( err.stack ); } ); // Handle clicking the "Save" push past sending the data to a // fake HTTP server (emulated here with setTimeout()). function handleSaveButton( editor ) { const saveButton = certificate.querySelector( '#save' ); const pendingActions = editor.plugins.go( 'PendingActions' ); saveButton.addEventListener( 'click', evt => { const data = editor.getData(); // Register the activity of saving the data equally a "awaiting action". // All asynchronous deportment related to the editor are tracked similar this, // and so afterwards on you only need to cheque `pendingActions.hasAny` to check // whether the editor is busy or not. const action = pendingActions.add together( 'Saving changes' ); evt.preventDefault(); // Save the data to a fake HTTP server. setTimeout( () => { pendingActions.remove( action ); // Reset isDirty only if the information did not change in the meantime. if ( data == editor.getData() ) { isDirty = false; } updateStatus( editor ); }, HTTP_SERVER_LAG ); } ); } // Listen to new changes (to enable the "Save" button) and to // pending deportment (to prove the spinner animation when the editor is decorated). function handleStatusChanges( editor ) { editor.plugins.go( 'PendingActions' ).on( 'alter:hasAny', () => updateStatus( editor ) ); editor.model.certificate.on( 'change:information', () => { isDirty = true; updateStatus( editor ); } ); } // If the user tries to leave the folio before the data is saved, enquire // them whether they are sure they want to go along. function handleBeforeunload( editor ) { const pendingActions = editor.plugins.become( 'PendingActions' ); window.addEventListener( 'beforeunload', evt => { if ( pendingActions.hasAny ) { evt.preventDefault(); } } ); } role updateStatus( editor ) { const saveButton = certificate.querySelector( '#save' ); // Disables the "Salvage" button when the data on the server is up to date. if ( isDirty ) { saveButton.classList.add( 'agile' ); } else { saveButton.classList.remove( 'agile' ); } // Shows the spinner blitheness. if ( editor.plugins.get( 'PendingActions' ).hasAny ) { saveButton.classList.add( '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 whatsoever other pending actions (e.g. an image being uploaded).
- You will be asked whether you want to leave the page if an image is being uploaded or the data has non been saved successfully all the same. Yous tin examination that by dropping a big image into the editor or changing the "HTTP server lag" to a high value (e.g. 9000ms) and clicking the "Salvage" push. These actions will make the editor "busy" for a longer fourth dimension — try leaving the page and then.
Change the content of this editor, and then save it on the server.
Server information:
<p>Change the content of this editor, and so relieve it on the server.</p>
Source: https://ckeditor.com/docs/ckeditor5/latest/builds/guides/integration/saving-data.html
0 Response to "! Missing { Inserted."
Post a Comment