TinyMCE not working in http request xhr ajax generated page - ajax

So i I have a page that contains links that call an httpRequest. The request calls a php file that grabs data from mysql and pre populates a form which is then returned to the browser/webpage. My problem is that when the page is returned to the browser via the httpRequest/ajax the text area does not display the tinymce editor, it just displays a normal text area. It looks like my request and ajax is working fine the text area just doesn't have the tinycme editor on it.
When i don't use ajax it works fine but when i put it in a separate file and call it via ajax it doesn't bring in the tinymce editor.
Does anyone know how to fix this problem so that my ajax generated page displays the text area with the tinymce editor. Thank you.

Lets presume that your thinyMCE instance is initialized with code below
// initialize tinyMCE in page
tinyMCE.init({
mode: "textareas",
theme: "advanced"
});
and you have some kind of button somewhere in the page. For purpose of this tip, i will not give it any ID but you may. Now, using jQuery you can easily attach event handler to that button which will call through AJAX your server and take content which you want to put tinyMCE editor. Code which will do such job would look somehow like below.
$(function() {
$("button").bind("click", function() {
var ed = tinyMCE.get('content');
ed.setProgressState(1); // Show progress
$.getJSON('/page/12.json', { /* your data */
}, function(data) {
ed.setProgressState(0); // Hide progress
ed.setContent(data["body"]);
}
});
});
});
You can see that on button.click ajax will call url /page/12.json which will return JSON as response. bare minimum of that response could be:
{
title: "Page title",
body: "<html><head><title>Page title</title>......</html>"
}
I attached anonymous function as callback which will handle response from server. and hide progress indicator which is shown before ajax call.
About JSON
JSON is shorten of JavaScript Object Notation. It is JavaScript code!!! So don't be confused about it. Using JSON you can make javascript object which can have attributes you can use later in your code to access particular peace of data which that object "holds". You can look at it as some kind of data structure if it is easier to you.
Anyway, to show you how this JSON can be created by hand look at examples below
var data = new Object();
data.title = "Page title";
data.body = "<html....";
or
var data = {
title: "page title",
body: "<html...."
};
it is very same thing.
If you want to learn more about JSON point your browser to http://json.org.
===== alternative =====
Alternative to json solution could be just plane ajax call to server and response can be plain HTML (from your question I can assume that you have something like this already). So instad of calling $.getJSON you can use $.get(url, callback); to do same thing. The code at the top of my answer will not dramatically change. Instead of geting JSON in response you will get string which is HTML.
----------- BOTTOM LINE -------
I prefer JSON since it can be easily extended later with other attributes, so there is no painful code changes later ;)

Problem here will be that when you return the full page and render it using the ajax response, your tinymce instance has not been shut down before.
In order to do this you can call this small piece of code before you render the ajax response:
tinymce.execCommand('mceRemoveControl',true,'editor_id');
In this case the editor should initialize correctly. You are not allowed to initialize a tinymce editor with the same id before shutting the first one down.

Strangely i ran into this problem yesterday. Following code should work, but YMMV. Trick is to use the correct steps in ajax events. I used the Regular TinyMCE and made use of the jQuery library already included.
Following goes into your tinyMCE initialization tinyMCE.init() . All of the below block should be outside the document.ready.
myTinyInit = {
//.......All essential keys/values ...........
setup : function(ed) {
ed.onChange.add(function( ed ) {
tinyMCE.triggerSave();
}) }
//.....................
};
// Init the tinyMCE
tinyMCE.init(myTinyInit);
This ensures the content is being saved regularly onto the textarea that holds the value. Next step is setting up the request events.
Normally tinyMCE mceAddControl before the ajax post and mceRemoveControl after the ajax success should do the trick. But I found that often does not work.
I used the form as the jQuery selector in my case.
jQuery( '.myForm' )
.find( 'textarea#myTextArea' )
.ajaxStart(function() {
// If you need to copy over the values, you can do it here.
// If you are using jQuery form plugin you can bind to form-pre-serialize event instead.
// jQuery( this ).val( tinyMCE.get( jQuery( this ).attr( 'id' )).getContent() );
}).ajaxSend( function() {
// ! - step 2
// My case was multiple editors.
myEds = tinyMCE.editors;
for( edd in myEds ) {
myEds[ eds ].remove();
}
// tinyMCE.get( 'myTextarea' ).remove();
// strangely mceRemoveControl didnt work for me.
// tinyMCE.execCommand( 'mceRemoveControl', false, jQuery( this ).attr('id'));
}).ajaxSuccess(function() {
// Now we got the form again, Let's put up tinyMCE again.
txtID = jQuery( this ).attr( 'id' );
// ! - step 3
tinyMCE.execCommand( 'mceAddControl', false, txtID );
// Restore the contents into TinyMCE.
tinyMCE.get( txtID ).setContent( jQuery( this ).val());
});
Problems i came across :
Using mceRemoveControl always gave me r is undefined error persistently.
If you get a blank tinyMCE editor, check the DOM whether the ID of the textarea is replaced with something like mce_02, this means that TinyMCE is being initialized again or something is wrong with the order. If so, the tinyMCE is duplicated with each save.
if you are new to JS, I recommend using jQuery with the form plugin, it might be easier for you. But do use the regular non-jquery tinyMCE, as it is well documented.

I fixed this problem by recalling the function after the ajax call. In this part of my ajax:
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("Content").innerHTML=xmlhttp.responseText;
tinymce();
Now it works fine.

Related

How do i request an Array from the controller from inside a javascript code

I am using Spring boot, JPA with mysql, and thymeleaf and openlayers for the map.
So i have a map, and on this map there are dynamically generated markers for different places. What I want is when I click any of those markers to send the name of the marker to my controller and in response get an array of fishes that can be caught in this specific area and then display the names and pictures of the fishes in a dynamically generated list located on the sidebar . I cant think on how I can achieve that. Ive made a HTML page to show how I want it to look.
I was thinking about making a get request and giving the name as a path variable but then idk how I can do that request from the javascript when the button is clicked. Any ideas or concepts that I can read about are apreciated.
Most DOM elements in html are accessible in javascript via something like document.getelementbyid and typically if I remember this correctly most of the objects you can do something like domobject.addEventListener("click", myScript); and in myScripy make an http call to spring requesting the list of fish. I recommend setting some breakpoints in your JavaScript code via the dev console in your browser and looking through some of the objects that are produced
You can make a get request like described here. developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
Clicking on the markers would be similar to this example https://openlayers.org/en/latest/examples/icon.html, but instead of showing a popup you make a GET request for more data
map.on('click', function (evt) {
const feature = map.forEachFeatureAtPixel(evt.pixel, function (feature) {
return feature;
});
if (feature) {
const name = feature.get('name');
// now make get request
// ....
}
});
If you are requesting an image you could use xhr as in https://openlayers.org/en/latest/apidoc/module-ol_Tile.html#~LoadFunction or you could use fetch, similar to:
fetch(url).then(function(response) {
if (response.ok) {
return response.blob();
}
}).then(function(result) {
if (result) {
const imagesrc = URL.createObjectURL(result);
}
});

Save edited inline text from CKEditor 4 asp net

I am trying to implement CKEditor 4 into an ASP NET website that I am working on, but I cannot figure out how I would save the edited material from the inline editor I know how to do it with the the old version, but I just don't understand the process for this.
I have looked in the forums... There is not v4 forum.
I looked in for the documentation.... Couldn't find it.
I have a feeling that this is a simple task, but I just don't know how.
You can get your data with CKEDITOR.instances.editor1.getData(). Then you can send it via AJAX or store it as a value of some input field. To do this periodically, follow this method:
CKEDITOR.disableAutoInline = true;
var editor = CKEDITOR.inline( 'editable' );
var savedData, newData;
function saveEditorData() {
setTimeout( function() {
newData = editor.getData();
if ( newData !== savedData ) {
savedData = newData;
// Send it with jQuery Ajax
$.ajax({
url: 'yourUrl',
data: savedData
});
// Or store it anywhere...
// ...
// ...
}
saveEditorData();
}, 500 );
};
// Start observing the data.
saveEditorData();
You can also observe the submit event and update some (hidden) form field with your data.
Have fun!
Are you trying to get it with AJAX or send with a form? The value of for example the top right inline editor area with Lorem Ipsum can be gotten like in the older version with simply
CKEDITOR.instances.editor1.getData().
In the XHTML output example they have a simple form that seems to work and I believe that using an (static) inline editor is just the same.
If you transform elements into editors inline dynamically, I would try to bind to the submit event and before submitting loop through all CKEDITOR.instances, get their data into hidden from fields. As for the hidden field naming or identifying which hidden field corresponds to which dynamic editor you'll have to figure out yourself :)

Running a javascript after ajax load

I'm using jQuery UI. I'm loading some content in a dialog box over AJAX. After inserting the content from the server, I need to make modifications to the document. I am using the .live() function on my link; I thought this would enable me to use Js after loading the content over ajax, but it's like the content I just loaded isn't a part of the document. Any help very much appreciated.
Are you adding the bindings (lives) in the success function of the ajax call?
If so I had the same issue, I'll try to explain what I figured out:
$.post('callURL', function(data){
// Let's say data returned from server is an ID of a div I have to hide
// by clicking on some_link
$('#some_link').live('click',function(){
$('#'+data).hide();
});
});
This won't work because the code inside the 'live' function is executed on click and at that time the 'data' value is gone.
To make it work I made a global variable 'ID' which I set in the success function and then called in the 'live' function again like this:
var ID;
$.post('callURL', function(data){
// Let's say data returned from server is an ID of a div I have to hide
// by clicking on some_link
ID = data
$('#some_link').live('click',function(){
$('#'+ID).hide();
});
});

MVC2 - Submit form with AJAX and non-AJAX

Using MVC2 I have created a form using the Ajax helper in a view. The form posts to a controller which binds to a model object. A PartialViewResult is returned by the controller and the HTML gets updated into a div. So far, so good.
I now need to submit the same form and return the results in a generated file for the user to download. Obviously I don't want the file contents going into my div.
Is there an elegant way to handle this situation without having to hack it to bits? I'm fairly new to MVC / AJAX and it's still a point of confusion for me.
You may not use ajax call to download files. Following links may help you to do what you are trying to do
JQuery Ajax call for PDF file download
http://forums.asp.net/t/1683990.aspx/1
OK, so I couldn't find any simple solutions anywhere so I came up with my own. I remove the Ajax event handlers from the form when I want the download, put them back when I want the Ajax. I'm guessing there's a more elegant way to do this, as this feels like a 'clever trick'. I'm open to better suggestions but so far this is my preferred method.
Reference ToggleAjax.js on my page:
var ToggleAjax = function ($, form) {
var onclick = form.onclick,
onsubmit = form.onsubmit;
$('input[class*="ajax-enabled"]').click(function () {
form.onclick = onclick;
form.onsubmit = onsubmit;
});
$('input[class*="ajax-disabled"]').click(function () {
form.onclick = function () { };
form.onsubmit = function () { };
});
};
Then I call ToggleAjax on my page and pass in the form:
$(function () {
ToggleAjax($, $('form')[0]);
});
And of course I add the class ajax-enabled or ajax-disabled to the input controls.

Submiting a form from ajax outside the page (php)

I use JQuery to insert a form into a div, the form is in a php file.
function show(id){
var content = $("#layer1_content");
$("#layer1").show();
var targetUrl = "mouse.php?cat="+id;
content.load(targetUrl);
}
Everything works, but when I submit it goes to that php page. Ff I call the same form within the same php then it works fine. The response is handled by:
$('#layer1_form').ajaxForm({
target: '#content',
success: function()
{
$("#layer1").hide();
}
});
Your question is not super clear but my hunch is that in the case when it does not work, you are actually submitting the form. This would cause the page reload.
Try grabbing the form and attaching a submit handler that cancels the submit:
$('form').submit(function(){ return false; });
hey, thanks for reply, i just fixed it but in a very cheap manner.
Il try explain again, my jquery gets the contents from a php file like so:
stuff....here..
this calls a div that pops up:
function show(id)
{ var content = $("#layer1_content");
$("#layer1").show();
var targetUrl = "mouse.php?cat="+id;
content.load(targetUrl);}
and this is supposed to submit and send back the results from the php "savesettings"
$('#layer1_form').ajaxForm({
target: '#content',
success: function()
{
$("#layer1").hide();
}
});
above : #content is were the output will show.
layer1 is the div that holds the form.
if #layer1 div is were my javascript is then, everything works, and the #content div receives the info. But i cant put it the form in the same file cause it will contain alot of settings that will fill the page horribly.
so what i did was (and this is cheap of note i am sure)
this, i took all the stuff inside the form, and called it externally, so that did the trick but it feels cheap :
Iput i new div hre
you think my solution is pathetic?

Resources