14-day Cloud trial
Start today. For free.

One editor. 50+ features. Zero constraints. After your trial, retain the advanced features.

Try Professional Plan for FREE
PricingContact Us
Log InGet Started Free

How to load and post Ajax content in TinyMCE

May 18th, 2022

5 min read

TinyMCE save and post with Ajax and a clock representing timeout

Written by

Joe Robinson

Category

How-to Use TinyMCE

An essential function for websites is the ability to update and change content without a page refresh. That’s what Ajax does. (Weird name isn’t it.) It used to mean “Asynchronous JavaScript And XML”, but the name Ajax has evolved to mean a development technique making use of asynchronous processing.

With Ajax, you can load, change, and post content to modify how your website appears to your customers. More importantly though, you can make these changes asynchronous.

Why is Ajax important?

Ajax processes don’t hold up the loading process of an entire web page. Instead, it allows for changes to web pages to happen as needed, rather than having to reload the entire website's page. That would be frustrating. Not something to do in front of the customer.

Thankfully, TinyMCE’s rich text editing abilities include working with asynchronous functions. It works in situations where web elements need text entry with load and post methods (like a form for instance).

This article explains Ajax post and load. The first demo shows how to get started with asynchronous actions using TinyMCE. The second delves into Ajax – how to load and use Ajax post techniques with TinyMCE.

How can TinyMCE handle asynchronous events?

To configure this functionality correctly, it’s worth using the setProgressState() TinyMCE API method. This provides a useful loading animation. Playing the animation eases loading events for your customers.

Also the setTimeout() global method (an asynchronous method). This method is useful for coordinating asynchronous events.

For load and post Ajax actions, it’s a useful addition to try out the setProgressState() API. This way, you can get an idea of how to set up and load content.

How to load asynchronous content with TinyMCE

  1. Create a new index.html file within your development environment.

  2. Sign up for a TinyMCE account to get your FREE API key. You’ll need the key to prevent any error messages appearing in the text area. It stops the nag.

    It will also give you access to TinyMCE's premium features for 14-days, free.

  3. Include the Tiny Cloud link and the tinymce.init script in your index.html file. Replace no-api-key with your TinyMCE API key. 

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TinyMCE and AJAX</title>
    <script src="https://cdn.tiny.cloud/1/no-api-key/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script>
    <script>
        tinymce.init({
            selector: "#mytextarea",
        });
    </script>
</head>
  1. Set up the HTML content to load TinyMCE in the demo. This demo includes an HTML button element.

<body>
    <textarea name="" id="mytextarea" cols="30" rows="10">
        <h2>TinyMCE Content</h2>
        <p>TinyMCE Content</p>
        <p>Your TinyMCE content.</p>
    </textarea>
    <button>Add new content</button>
</body>
  1. Include a script after the </body> close tag to select the button element

<script>const button = document.querySelector('button');</script>;
  1. Add an event listener function to the script tags after the button query selector, and include inside it the setProgressState API method:

<script>
const button = document.querySelector('button');
      button.addEventListener('click', event => {
            tinymce.activeEditor.setProgressState(true)
            tinymce.activeEditor.setProgressState(false, 3000)
            setTimeout(() => {tinymce.activeEditor.setContent(
                '<h2>TinyMCE New Content</h2><p>TinyMCE New Content</p><p>Your New TinyMCE content.</p>'
            )},2000);
</script>
  1. Save the changes, and open the index.html file in your browser. You can do this using the python -m http.server 8000 command to run the demo as close to a production website as possible:

TinyMCE save asynchronous event running in the demo

How about TinyMCE and Ajax?

It’s possible to configure and try out TinyMCE with an asynchronous, Ajax post event. The following example uses an Ajax post event is a form.  

TinyMCE works well in forms, and the following example uses TinyMCE with inline mode and the menubar and toolbar switched off.

How to configure TinyMCE with an Ajax load event

  1. Create a new index.html file, and include the TinyMCE Cloud and tinymce.init script: 

<script src="https://cdn.tiny.cloud/1/no-api-key/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script>
    <script>
        tinymce.init({
            selector: ".myeditor",
            menubar: false,
            toolbar: false,
            inline: true,
        });
    </script>
 
Note: Inline mode means that Tinymce works on an HTML element other than the <textarea> element.
  1. Include a link to the Ajax, jQuery cdn next to the TinyMCE sript.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>;
  1. Configure the page HTML, which includes TinyMCE inside a form element, specifically initializing TinyMCE on the <div> element.
<h2>TinyMCE AJAX POST</h2>
<form id="register" action="registry.php" method="POST">
  <label>Content<div class="myeditor"></div></label>
  <input type="submit" value="Post Content"/>
</form>
  1. After the page </body> closing tags, add the following jQuery script example into your index.html file. This script includes the jQuery $.post method, which is shorthand for the Ajax post method:
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType});

Shorthand with jQuery >>>

$.post("url", data, function() {});

The example:

<script>
    $('#register').on('submit', function(ed) {
      tinymce.triggerSave();
      ed.preventDefault();
      var TinyAjaxPost = $('#register').serialize();
      $.post('registry.php', TinyAjaxPost, function(data) {
        $('#register').html(data);
      });
    });
  </script>
  1. Save the changes to the file, and then create the registry.php file in the same directory that you created the index.html file. Place the following PHP script into the registry.php file:
<?php
echo '<p>The <strong>POST</strong> worked if you can see this'
?>
  1. Save the changes, and then load the index.html file in your browser. Instead of using the python http.server command, make use of the PHP Development server command. Run php -S localhost:8000 on the command line inside the same directory as your index.html and registry.php file.

TinyMCE running an asynchronous Ajax POST

How to configure TinyMCE with Ajax asynchronous posts

With some adjustments to the previous demo, it's possible to test out the TinyMCE setProgressState  method with Ajax.

The only adjustments needed are the following:

  1. Change the tinymce.init script to turn the menubar, toolbar, and inline values to false. This changes TinyMCE out of inline mode:
<script>
  tinymce.init({
    selector: ".myeditor",
    menubar: true,
    toolbar: true,
    inline: false,
});
</script>
  1. Replace the form contents with a <div> element and a <button> element:
<form id="register" action="registry.php" method="POST">
  <div class="myeditor"></div>
  <button name="Ajax Post" value="Save">Add new content</button>
</form>
  1. Adjust the jQuery script so that the setProgressState methods and the setTimeout method run with the Ajax post:
<script>
  $('#register').on('submit', function(ed) {
    tinymce.activeEditor.setProgressState(true);
    tinymce.triggerSave();
      setTimeout(() => {
        ed.preventDefault();
        var TinyAjaxPost = $('#register').serialize();
        $.post('registry.php', TinyAjaxPost, function(data) {
          tinymce.activeEditor.setProgressState(false, 2000);
          $('#register').html(data);
        });
      },2000);
  });
</script>

  1. Adjust the message in the registry.php file (to stop this procedure being too close to the last one:
echo '<div>Thanks for trying out the Ajax <strong>POST</strong> with TinyMCE!</div>'
  1. Save the changes, and run the demo in the browser with the PHP development server. The TinyMCE setProgressState makes a brief appearance before the Ajax Post:

TinyMCE Ajax load and save content with asynch features

Go further with Ajax and TinyMCE

Ajax and asynchronous processes are important functionality for websites. With TinyMCE, you can introduce content into the rich text editor, and then make use of Ajax POST methods to send the data to your server (or to a .php file, as seen in the above example).

TinyMCE also works with asynchronous functions and in production, you can configure the different TinyMCE API methods to provide your customers with a solid UX.

You can explore TinyMCE APIs further by checking on these guides: 

When you sign up for a FREE API key, you gain access to a wider range of functionality as well  as the Power Paste plugin for clean copy paste, and access to more skins and icons.

Contact us if you need more information about TinyMCE’s Premium Plugins, or APIs with asynchronous methods.

APITinyMCEConfigurationDevelopers
byJoe Robinson

Technical and creative writer, editor, and a TinyMCE advocate. An enthusiast for teamwork, open source software projects, and baking. Can often be found puzzling over obscure history, cryptic words, and lucid writing.

Related Articles

  • How-to Use TinyMCEMar 28th, 2024

    How to view and restore document version history in TinyMCE

Join 100,000+ developers who get regular tips & updates from the Tiny team.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Tiny logo

Stay Connected

SOC2 compliance badge

Products

TinyMCEDriveMoxieManager
© Copyright 2024 Tiny Technologies Inc.

TinyMCE® and Tiny® are registered trademarks of Tiny Technologies, Inc.