"Enable real-time editing with inline save/submit feature in

I'm struggling to figure out how to extract the modified content from a CKEditor instance and send it to a URL.

I've been referencing something like this:

but I can't seem to determine how to save the changes. Is there a way to post the updated data to a PHP file along with the ID of the edited element?

Just like this example:

editor.on('configLoaded', function(){
    // do some operations
});

I was hoping to achieve something similar with this code snippet:

editor.on('clickAway', function(e){
    id = e.id();
    // perform AJAX actions
});

However, my search has not led me to any solutions so far.

Has anyone successfully implemented this feature before?

Appreciate your help.

Answer №1

There are countless approaches to achieving this, and here's how I tackled it using the Smarty Template Engine. However, this method should be adaptable to plain HTML as well.

To begin with, consider the following sample HTML snippet from my "dog_fleas.tpl" template file:

<script type="text/javascript" src="/js/ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="/js/admin/mycms.js"></script>
<div>
  <div id="flea-blurb" tpl="/templates/dog_fleas.tpl" contenteditable="true">
    <h1>My Dog Has Fleas</h1>
    <p>This text is editable via the CMS!</p>
  </div>
  <p>This text is not editable</p>
</div>

Below is the JavaScript code (mycms.js) responsible for managing the inline editing functionality:

$(document).ready(function() {

    CKEDITOR.disableAutoInline = true;

    $("div[contenteditable='true']" ).each(function( index ) {

        var content_id = $(this).attr('id');
        var tpl = $(this).attr('tpl');

        CKEDITOR.inline( content_id, {
            on: {
                blur: function( event ) {
                    var data = event.editor.getData();

                    var request = jQuery.ajax({
                        url: "/admin/cms-pages/inline-update",
                        type: "POST",
                        data: {
                            content : data,
                            content_id : content_id,
                            tpl : tpl
                        },
                        dataType: "html"
                    });

                }
            }
        } );

    });

});

The provided script carries out a few key tasks:

  1. It converts any div element with the attribute contenteditable set to "true" into an editable region.
  2. Upon editing the content (on blur), the ID of the edited element, template filename, and modified content are transmitted to the server via an ajax call.

In my scenario, the tpl attribute serves to identify the file being edited while the element ID specifies the altered element.

While my example showcases a single editable area, this solution supports multiple editable regions within a single file.

On the server side, refer to the PHP code below. Please note that I'm working within a framework, so there may be differences in the syntax utilized compared to standard PHP functions:

... (remaining content similar to original response)

I recognize that regular expressions might not always be the optimal choice. For more straightforward systems, you may want to explore employing the PHP Dom Object Model instead if your HTML conforms to valid standards.

I trust this explanation proves beneficial!

Answer №2

Here is the solution that worked for me: How to save changes made in an inline editor to the server?

I have implemented the blur event method

Answer №3

Enhancing the solution provided by @clone45, I have made some modifications. The updated data will now be saved using the Save button only after comparing the old and new data.

I have overridden the existing save button of the inline editor and incorporated the essential part from @clone45's answer below.

<script>

CKEDITOR.disableAutoInline = true;
$("div[contenteditable='true']").each(function(index) {
    var content_id = $(this).attr('id');
    var tpl = $(this).attr('tpl');
    var oldData = null;
    CKEDITOR.inline(content_id, {
        on: {
            instanceReady: function(event) {
                //get current data and save in variable
                oldData = event.editor.getData();
                // overwrite the default save function
                event.editor.addCommand("save", {
                    modes: {
                        wysiwyg: 1,
                        source: 1
                    },
                    exec: function() {
                        var data = event.editor.getData();
                        //check if any changes has been carried out
                        if (oldData !== data) {
                            oldData = data;
                            $.ajax({
                                    type: 'POST',
                                    url: 'process.php',
                                    data: {
                                        content: data,
                                        content_id: content_id,
                                        tpl: tpl
                                    }
                                })
                                .done(function(data) {
                                    alert('saved');
                                })
                                .fail(function() {
                                    alert('something went wrong');
                                });
                        } else
                            alert('looks like nothing has been changed');
                    }
                });
            }
        }
    });
});

</script> 

This revised version should be more efficient for managing your data!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving text that has been HTML-escaped from a textarea using jQuery

Within my HTML file, I have a <textarea id="mytextarea"></textarea>. Suppose a user inputs the following text: <hello>, world! How can I retrieve res = "&lt;hello&gt;, world!"; based on the user's input? The current code s ...

Unresolved styles in React component linked to styles.css file

As I dive into creating a registration page in ReactJS, I encounter a frustrating issue with my styles not applying correctly from the styles.css file. Let's take a look at my RegisterPage.jsx component: export default function RegisterPage() { ret ...

Does PHP/AJAX only function when an output is generated?

I am attempting to fetch the Wordpress blog header into a php file in order to use it for an AJAX call function. define('WP_USE_THEMES',false); echo 'Something'; require(explode("wp-content",realpath(dirname(__FILE__)))[0].'wp-b ...

Performing two AJAX POST requests in the Laravel framework

After searching on Stack Overflow with the same title, I had no luck finding a solution. Here is my AJAX script: $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('input[name="_token"]').val() } }); $(&apo ...

What is the best way to utilize a JavaScript function across all pages in Drupal 7?

What is the best way to utilize a global JavaScript function in Drupal 7? I have structured my JavaScript file as follows and included it using drupal_add_js(): (function($) { function add_if_country_is_not_usa() { // Determine the current country ...

Can you please explain the distinction between the statements var a = b = 2 and var a = 2; var b = 2;

Whenever I try to declare a variable within a function, I encounter an issue. var b = 44; function test(){ var a = b = 2; } However, the following code works without any problems: var b = 44; function test(){ var a; var b = 2; } The global ...

Unable to dynamically add an element to a nested array in real-time

I'm currently developing an angular tree structure that contains a large nested array. nodes : public fonts: TreeModel = { value: 'Fonts', children: [ { value: 'Serif - All my children and I are STATIC ¯\ ...

The disappearing act of the Show/Hide Button in Sencha Touch 2.3.1: what's the

I'm running into an issue with my sencha touch app. Here is the container I have defined: { xtype: 'container', text: 'SOMETHING', height: '15%', width: '15%', ...

Are you a fan of Ajax calls using JSON or HTML?

Which method is most recommended for implementing AJAX? If you were developing a search page using PHP and Jquery for the AJAX calls, how would you manage the response? a) Would you prefer to have the response include all relevant HTML and styling? or ...

Discover the power of EJS embedded within HTML attributes!

There are two cases in which I am attempting to use an EJS tag within an HTML attribute. SITUATION 1: <input style="background-image: url(<%= img.URL %>)" /> SITUATION 2: <input onchange="handleCheckboxChange(<%= i ...

Navigating in Angular with parameters without modifying the URL address

In a nutshell, my goal is to navigate to a page with parameters without showing them in the URL. I have two components: Component A and B. What I want to do is route to B while still needing some parameters from A. I know I can achieve this by setting a ...

"Discover the power of D3.JS with three dazzling charts on a single page, plus a host of additional

As a student, I struggle with English and it makes me feel sorry and anxious... Despite that, I want to create three scatter plot charts on the same page using a single data file (csv). The dataset includes columns for Name, Height, Weight, and Grade (ra ...

Tips for displaying Japanese characters followed by numbers in a single line on a web browser using CSS

Combining Japanese characters with numbers without spacing can present formatting challenges. For example, with a string like "新しいフォルダ000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 ...

The process of departing a SocketIO room and switching to a different room logic

I am wondering how I can leave the Room when I click on a new Room Here is what my page looks like: The list on the left side is from the MySQL Server and it displays a list of my chats. Each Room name has an id value which corresponds to the room name, ...

Is there a way to utilize a POST request to pass a React component from server.js to App.js for rendering?

I am new to React and JavaScript and still in the learning process :) I'm working on a magic 8 ball application where, upon clicking the button using the post method, I aim to retrieve a random answer (one of the 20 in my server.js) back to the same ...

Interact with the exe/jar files on a remote machine using JavaScript

I've been tasked with finding a way to access an executable file (or any file located in a specific location like the C drive) directly from a web browser. The idea is to have a button on a webpage that, when clicked, will run the executable and pass ...

The useSelector value remains undefined within the handleSubmit button in a React component

Once a user fills out and submits the form, the action is triggered to call the API. Upon returning the postId, it is stored in the reducer. The main React component then utilizes useSelector to retrieve the latest state for the postId. However, when attem ...

Executing python code from a JavaScript (Node.js) program without the need to create a child process

I have a unique setup where my hardware is running on nodejs, while my machine learning code is written in python3. My goal is to invoke the python3 program from nodejs (javascript) and pass data as arguments to the Python script. While researching, I cam ...

Is it possible for a JSON array to consist of objects with varying key/value pairs?

Is it possible for a JSON array to contain objects with different key/value pairs? The example provided in this tutorial shows objects within the JSON array having the same key/value pair: { "example": [ { "firstName": " ...

Stop receiving notifications for channel events in Stream with the GetStream.io Chat API

I'm having trouble understanding how to stop listening for channel events in JavaScript using the Stream Chat API. According to the documentation: // remove the handler for all "message.new" events on the channel channel.off("message.new", myChanne ...