I am Using Cl Editor On a Cms in a working on, Everytime i submit data through ajax i am having problems with it.
Let's say i write 10 lines in my wysiwyg editor but i only receive 3 or 4 in php, after some debugging in firebug what i have noticed is the html i am sending through ajax contains a span with class "Apple-converted-space" <span class="Apple-converted-space"> </span> i am able to get everything before this span, but the text after this span is missing. I have no idea what it is. Let me write my code for better understanding.
To get cleditor data
var data = $(".cleditorMain iframe").contents().find('body').html();
Ajax Form Submission
if(window.XMLHttpRequest)
{
xmlhttp = new window.XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == '4' && xmlhttp.status == '200')
{
}
}
parameters = 'data=' + data
xmlhttp.open('POST', 'libs/make_procedure.php', true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.send(parameters);
return true;
I have also tried jquery ajax method.. same problem exists there, so please do not ask me to use the other way to submit data via ajax.
Thanks
You may want to check whether it is javascript that is not sending correct data or your backend that is not able to receive it.
So first you should debug in javascript by writing an alert(data); statement right after you get the data from that cieditor control, and see what do you get there. Use Firefox and you can also copy the html using mouse pointer from the alert box. (which is not possible in IE)
You should also check the cieditor specs to see if there is any easier way to get data in javascript.
You may also want to consider using CKEditor.
You are posting the data without escaping the contents of the data. Since the & is the seperator for different fields in a post, data will contain only the part up untill the first &. Use encodeURIComponent to escape the data value.
Change the line
parameters = 'data=' + data
to
parameters = 'data=' + encodeURIComponent(data);
See also: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/encodeURIComponent
Related
I´m trying to do this:
var http = new XMLHttpRequest();
var url = "guardarImg.php";
var params = $('#form').serialize();
http.open("POST", url, true);
http.setRequestHeader("Content-type", "multipart/form-data");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
But is not working, it shows me in my php that 'Image' is not defined, but when I do it through a average Submit it works fine.
All the similar samples I saw work with string data but I need to achieve it with images to make it work later in Intel XDK
What I´m doing wrong?
Can you show me a sample?
Sorry if my question is too basic, I´m a noob with xmlhttp and ajax stuff.
You have the right idea with regard to $("#form").serialize() but for the mess that is (still) AJAX uploads. Yuck (and shame on me for not noting that detail the first time :-( ).
The problem with file uploads via AJAX is (as is often the case), Internet Explorer. Basically, it didn't support the FormData object until IE10 (which means that, if you care about supporting XP users, they'd better be running not-IE). FormData greatly simplifies the process of uploading stuff via AJAX; if you don't have that, here are your options:
Put a little tiny IFRAME on the page and manage that for the actual file upload.
Encode the form data programmatically using something like JSON and send that via jQuery.
Use a nice plugin that wraps this all for you (and uses one or more of these techniques under the covers).
I'm going to assume you don't care about IE8/9 (pretty much everyone else isn't a problem) and give you a FormData solution. Unlike the previous edit, I'm popping in the whole function in here since it's decently informative. This particular solution uploads an entire form, pulling in the existing fields into the FormData object and treating the files specially.
<!-- Many ways to skin this particular feline; I like this one :-) -->
<form onsubmit="return uploadFiles(this)">
<!-- Access from PHP using $_FILES["somefile"]["name"][$idx]... -->
<input type="file" name="somefiles" multiple="1" />
</form>
<script>
// Function to upload a form via FormData, breaking out files and cutting
// any non-named elements. Assumes that there's a #status DIV and the
// URL is hardcoded.
function uploadFiles(frm) {
var formdata = new FormData();
// I'm doing this to separate out the upload content. Note that multiple
// files can be uploaded and will appear as a decently-friendly PHP array
// in $_FILES. Note also that this does handle multiple files properly
// (a default FormData(frm) wouldn't exactly :-( ).
$(frm).find(":input").each(function(idx, ele) {
// This is a file field. Break it out.
if(ele.files) {
for(i=0; i<ele.files.length; i++) {
formdata.append(ele.name + "[" + i + "]", ele.files[i]);
}
// Not a file element, so put in the upload iff there's a name.
} else if(ele.name) {
formdata.append(ele.name, ele.value);
}
});
// Run the AJAX.
$.ajax({
url: "test.php", // Change Me :-)
type: "POST",
data: formdata,
processData: false, // Need these to keep jQuery from messing up your form
contentType: false,
success: function(data) {
$("#status").html(data);
},
error: function(xhr, status, error) {
$("#status").html("Error uploading file(s): " + error);
},
});
return false; // Keep the form from submitting
}
</script>
I have a complete HTML file and corresponding PHP that work at pastebin.
If I were you, I'd actually just use Sebastian's jQuery File Upload if you can. It's got all that modern UI goodness (include progress metering), browser abstraction, and it's MIT licensed to boot. That said, this answer will get you on your way if you just need something to copypasta. Good luck!
I'm new here but I found many help in the passt reading Q&A.
My problem is this:
in a HTML page I have a form with many fields, one of these is a SELECT with name and id "f_container"; I pose it inside a element (<div id=f_cont_ins></div>) ad use an AJAX function to populate it dynamically.
function ele_con(id,cod_cont) {
var http = createRequestObject();
http.open('get', 'fler.php?id='+id+'&art='+document.getElementById('stp').value);
http.onreadystatechange = function() {
if(http.readyState == 4){
var response = http.responseText;
document.getElementById('f_cont_ins').innerHTML = response;
}
}
http.send(null);
}
The "response" is right formatted an display right in the browser (Firefox); if I inspect the element or analyze the DOM structure it seems all ok, and I can get the value of a selection with document.getElementById('f_container').value.
But when I post the form, the field "f_cointainer" isn't present in the print_r($_POST); array, but all the other yes.
I navigate the net but don't found a clear ansver that these is not possible or a workaround to solve the problem.
I have an idea that is to use the document.location='page.php?par1=a&par2=b&f_container=5'; created reading value with document.getElementById, but I prefer a POST solution if it exist.
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 :)
Here is the problem:
By default jQuery Mobile is using GET requests for all links in the application, so I got this small script to remove it from each link.
$('a').each(function () {
$(this).attr("data-ajax", "false");
});
But I have a pager in which I actually want to use AJAX. The pager link uses HttpPost request for a controller action. So I commented the above jQuery code so that I can actually use AJAX.
The problem is that when I click on the link there are two requests sent out, one is HttpGet - which is the jQuery Mobile AJAX default (which I don't want), and the second one is the HttpPost that I actually want to work. When I have the above jQuery code working, AJAX is turned off completely and it just goes to the URL and reloads the window.
I am using asp.net MVC 3. Thank you
Instead of disabling AJAX-linking, you can hijack clicks on the links and decide whether or not to use $.post():
$(document).delegate('a', 'click', function (event) {
//prevent the default click behavior from occuring
event.preventDefault();
//cache this link and it's href attribute
var $this = $(this),
href = $this.attr('href');
//check to see if this link has the `ajax-post` class
if ($this.hasClass('ajax-post')) {
//split the href attribute by the question mark to get just the query string, then iterate over all the key => value pairs and add them to an object to be added to the `$.post` request
var data = {};
if (href.indexOf('?') > -1) {
var tmp = href.split('?')[1].split('&'),
itmp = [];
for (var i = 0, len = tmp.length; i < len; i++) {
itmp = tmp[i].split('=');
data.[itmp[0]] = itmp[1];
}
}
//send POST request and show loading message
$.mobile.showPageLoadingMsg();
$.post(href, data, function (serverResponse) {
//append the server response to the `body` element (assuming your server-side script is outputting the proper HTML to append to the `body` element)
$('body').append(serverResponse);
//now change to the newly added page and remove the loading message
$.mobile.changePage($('#page-id'));
$.mobile.hidePageLoadingMsg();
});
} else {
$.mobile.changePage(href);
}
});
The above code expects you to add the ajax-post class to any link you want to use the $.post() method.
On a general note, event.preventDefault() is useful to stop any other handling of an event so you can do what you want with the event. If you use event.preventDefault() you must declare event as an argument for the function it's in.
Also .each() isn't necessary in your code:
$('a').attr("data-ajax", "false");
will work just fine.
You can also turn off AJAX-linking globally by binding to the mobileinit event like this:
$(document).bind("mobileinit", function(){
$.mobile.ajaxEnabled = false;
});
Source: http://jquerymobile.com/demos/1.0/docs/api/globalconfig.html
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.