Loading tinyMCE via Ajax

Hi all,

I'm trying to use a tinyMCE text editor in my Rails app and am having
some problems. I'm trying to load a tinyMCE-enabled form dynamically
as the result of an Ajax call, i.e. I want to insert the form into a
page via Ajax. The Ajax stuff is handled by the Mootools framework.
There's a few posts about this out there, but none of them seem to
work for me.

The code I have behaves as follows:

Define a function init_mce() to call the tinyMCE.init() function:

function init_mce(){
  tinyMCE.idCounter=0;
  tinyMCE.init({
    mode: "textareas",
    editor_deselector: "no_mce",
    theme: "advanced",
    convert_urls: false,
    plugins: "emotions,preview",
  });
}

In the onComplete callback of my ajax request, call init_mce();

The javascript returned from this request does two things:

1. Replace the content of a div with a form:

<% remote_form_for :text, :url => some_url, :before =>
"tinyMCE.triggerSave();" do |f| %>
  <%= f.text_area :body, :style => "width:100%;height:100%;", :id =>
"for_mce", :class => "for_mce" %>
  <%= submit_tag "Save" -%>
<% end -%>

2. Activate the control and set it to send an ajax request rather than
a normal submit:

$$('#editor_window form').each(function(elem)
{elem.addEvent('submit',function(e){e=new
Event(e);tinyMCE.triggerSave();this.send();e.stop();}) });

$$('#editor_window textarea').each(function(elem)
{tinyMCE.execCommand('mceAddControl',false,elem.id);});

Sadly, this doesn't work. Has anyone found a working solution to this?

Many thanks,
Adam

What works for me:

     <% if request.xhr? -%>
       <%= javascript_tag("tinyMCE.execCommand('mceAddControl', false, 'thing_#{thing_number}_description');") -%>
     <% end -%>

Obviously the id is going to be your elem.id. The difference is that my command is inside the partial rhtml that also contains the text_area having the "thing_#{thing_number}_description". Also, my form_remote_tag has :before => "tinyMCE.triggerSave(true,true); tinyMCE.setContent('');"

Of course, this is still a 1.1.6 app (yeah, I know).

-Rob

Rob Biedenharn http://agileconsultingllc.com
Rob@AgileConsultingLLC.com

Hi Rob, thanks for that. Unfortunately it doesn't work for me. I think
it's because I use Mootools instead of prototype, and when I render a
partial via Ajax, scripts aren't evaluated; instead I have to call
things separately such as

page.replace_html...
page << "some_functions();"

so all the JS is decoupled.

Weirdly though, when I call page <<
"tinyMCE.execCommand('mceAddControl', false,
'thing_#{thing_number}_description');" after having done a
page.replace_html to insert a partial with a tinyMCE form in it, the
form is rendered as a regular text area instead of a tinyMCE text
area. Is the problem perhaps that the JS has to be evaluated inside
the <form> element? If so, is there any way around this?

Aha! Fixed it. I was rendering another editor in a hidden div that was
lost in some old code which was causing a conflict. Oops...