Refreshing JavaScript following AJAX request in JSF

Hey there, I'm encountering an issue with the TinyMCE editor. Whenever I try to open a modal dialog, the TinyMCE doesn't render properly.

Take a look at my code:

$(document).ready(function() {

    jQuery('.tinymce').on('show',function(e){
        initTinymce();
    });

});

function initTinymce(){
    tinymce.init({
        selector: ".tinymce",
        plugins: [
            "advlist autolink lists link image charmap print preview anchor",
            "searchreplace visualblocks code fullscreen",
            "insertdatetime media table contextmenu paste"
        ],
        toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image"
    }); 
}

This is how it appears in my page:

<div class="form-group">
                                <label>Conteúdo *</label>
                                <h:inputTextarea value="#{cursoMB.paginaConteudo.conteudo}"
                                    id="conteudo" required="true"
                                    requiredMessage="O conteúdo é obrigatório"
                                    styleClass="form-control tinymce">
                                </h:inputTextarea>
                            </div>

Here's the AJAX call I'm making:

<h:commandButton styleClass="btn btn-default" type="button"
                            value="Criar Página"
                            actionListener="#{cursoMB.novaPaginaConteudo()}">
                            <f:passThroughAttribute name="data-toggle" value="modal" />
                            <f:passThroughAttribute name="data-target"
                                value="#modalDialogPagina" />
                            <f:ajax execute="@this" render="modalPagina" />
                        </h:commandButton>

Any ideas on how I can resolve this issue?

EDIT 1

I also attempted to use jsf.ajax.addOnEvent but that didn't work either. The TinyMCE is still not rendering properly (console.log shows normally):

$(document).ready(function() {

    initTinymce();
    jsf.ajax.addOnEvent(ajaxHandleTinymce);
});

function ajaxHandleTinymce(data){
    console.log('ajaxHandle');
    initTinymce();
}

function initTinymce(){
    tinymce.init({
        selector: ".tinymce",
        plugins: [
            "advlist autolink lists link image charmap print preview anchor",
            "searchreplace visualblocks code fullscreen",
            "insertdatetime media table contextmenu paste"
        ],
        toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image"
    }); 
}

Answer №1

After making the ajax call, be sure to initialize your widget. You can do this by setting up a JavaScript event listener on the f:ajax element like so:

<f:ajax execute="@this" render="modalPagina" onevent="handleAjaxResponse"/>

function handleAjaxResponse(data) {
   if (data.status === 'success') {
      initTinymce();
   }
}

It is not advisable to utilize the jsf.ajax.addOnEvent callback in this scenario as it will result in the widget being initialized each time an ajax call is sent to the server.

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

Is the NPM package not being imported? How exactly is it being utilized?

mediacms-vjs-plugin is a unique plugin designed for Video.js. The MediaCmsVjsPlugin.js source code begins with: import { version as VERSION } from '../package.json'; import 'mediacms-vjs-plugin-font-icons/dist/mediacms-vjs-icons.css'; ...

Troubleshooting IE compatibility for $.trim() jQuery functionality

Having trouble with $.trim() not working in IE but works fine in Firefox. Any ideas why this might be happening? Thanks. $('#GuestEmailAddress').on('blur', function () { var $inputValue = $(this).val(); ...

Whenever trying to access data from the database using DataTable row(), it consistently remains undefined and fails to retrieve any information

While working on my application, I attempted to display all the data in a DataTable from the database. Unfortunately, instead of achieving this, I encountered an error from the server. Upon receiving the error, the dataTable object was displayed as follows ...

Remove duplicate entries and store them in an array while also applying an extra condition in JavaScript

I'm looking to filter a list of objects based on different city and state values, then create a new list of cities from the filtered objects where the temperature is less than 40. The condition is that both the state and city should not be the same. l ...

Nodejs encountered an authentication failure during the login process

I've developed an authentication API utilizing Sequelize ORM for a Mysql Database. Below is an image of the users model that I have integrated into my login authentication code. View users model image module.exports = (sequelize, Sequelize) => { ...

What methods can be used to manage keyup events?

After following a tutorial for my class project on creating a 'frogger-like' game, I encountered a challenge with implementing player movement using arrow keys. The event listener provided in the tutorial facilitated this movement: document.addE ...

What is causing the error when using Interfaces and Observable together?

I created a ToDoApp and integrated Firebase into my project, but I am encountering an error. ERROR in src/app/todo-component/todo-component.component.ts(25,7): error TS2740: Type 'DocumentChangeAction<{}>[]' is missing the following proper ...

Exploring methods to retrieve data from the web3 platform through Node.js

Is there a way to retrieve token information such as name, symbol, and decimals using Nodejs in conjunction with web3js? ...

Ways to modify the color of the legend text in a HighChart graph

Click here https://i.sstatic.net/iuPs4.png I am attempting to modify the color of the series legend text from black to any color other than black: $(function () { $('#container').highcharts({ legend: { color: '#FF0000', ...

The onChange method in React is failing to execute within the component

I am having trouble overriding the onChange method in a component. It seems like the method is not triggering on any DOM events such as onChange, onClick, or onDblClick. Below are the snippets of code where the component is rendered and the component itsel ...

Tips on attaching a class to elements in a loop when a click event occurs

In my HTML, I am displaying information boxes from an array of objects that are selectable. To achieve this, I bind a class on the click event. However, since I am retrieving the elements through a v-for loop, when I select one box, the class gets bound to ...

"Textarea auto-resizing feature causes an excessive number of unnecessary lines to be added

I have a textarea that is coded with jQuery to limit the characters to 11 per line and automatically resize based on the number of lines. However, when users click 'Enter' to add a new line, it adds multiple extra lines instead of just one. This ...

The function of cookieParser() is causing confusion

Having an issue that I've been searching for answers to without success. When using app.use(express.cookieParser('Secret'));, how can we ensure that the 'Secret' is truly kept secret? I'm feeling a bit lost on this topic. Is ...

Error: Attempting to access property 'navigate' of an undefined variable is not allowed

Hey there, evening everyone! I'm facing a bit of an issue when trying to click on the "login or register button" as I'm getting this error message: "TypeError: Cannot read property 'navigate' of undefined" I've made some small ad ...

Removing a selected row from a data table using an HTTP request in Angular 2

I am working with a table that has data retrieved from the server. I need to delete a row by selecting the checkboxes and then clicking the delete button to remove it. Here is the code snippet: ...

Handling Circular Dependency: Injecting a Service into an HTTP Interceptor in AngularJS

I'm currently working on developing an HTTP interceptor for my AngularJS application to manage authentication. Although the code I have is functional, I am wary of manually injecting a service as I believed Angular is designed to handle this process ...

Attempting to delete a record in a Node.js Express MongoDB Jade application

I am facing a challenge with my application as I attempt to incorporate a button that can delete an entry containing a date and link. When I trigger the button, I encounter an error message stating: Error 404 not found. The goal is to input the date and li ...

Issue with Color in Line Chart of Flot Version 0.8.2

While working on Flot line charts and customizing their colors, I came across a strange issue. Once I set the first 3 colors, the plot started using the last color for all the remaining lines. This behavior was unexpected and not the norm. What adds to th ...

rectangle/positionOffset/position().top/any type of element returning a position value of 0 within the container

While the height/position of the container is accurately displayed, attempting to retrieve the top position (or any position) of containing elements yields a return value of 0. Additionally, using .getBoundingClientRect() results in all values (top, left, ...

Exploring the possibilities of using JPEGcam in conjunction with the powerful

<script language="JavaScript"> webcam.set_api_url( 'test.php' ); webcam.set_quality( 90 ); // JPEG quality (1 - 100) webcam.set_shutter_sound( true ); // play shutter click sound </script> I am exploring the u ...