AJAX POST of tinyMCE contents - Character encoding of table entities - javascript

I'm using the tinyMCE editor plugin in my webpage.
When I use a simple HTML page post to post the contents to the backend PHP and save them to a database or file, all seems OK.
When I try to do the same using an AJAX post, I am finding it impossible to prevent encoding issues.
In particular (I'll escape it here) \&\n\b\s\p\; is being converted to  and a "-" character is being converted to �
I've tried a few suggestions but with little luck.
The suggestion is that it is either an issue with my charset or encoding.
My save function is as follows:
function letterSave(newfile,fname){
var newDate = new Date;
var uniq=newDate.getTime();
var input = $('#myTextareastdletter');
var contents=input.val();
var context='<?=(!strcmp($sessobj->mode,"SA_ViewAbs")?"A":"S");?>';
// alert(fname);
$.ajax({
type: "POST",
url: '<?=auto_version("./SVajaxSaveDocContents.php")?>?duff='+uniq,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: {'S_sessid' : '<?=$sessobj->sessionid?>', 'context' : context, 'contents' : encodeURIComponent(contents), 'fname' : fname, 'newfile' : newfile},
success: function(data){
data = JSON.parse(data);
fname=data[0];
newLetterList=data[1];
if (fname != 'FAIL') {
alert ('OK: Letter Contents Saved to File ('+fname+').');
var versionOutput = $('#popupOutput');
versionOutput.html('');
var box = $('#popupDisplay');
var cover=$('#coverDiv');
box.css({
display:"none"
});
cover.css({
display:"none"
});
var letterOutput = $('#AbsenceLetters');
letterOutput.html(newLetterList);
} else {
alert ('Sorry: Failed to Save Letter Contents!');
}
},
error: function(data){
alert ('Sorry: Failed to Save Letter Contents!');
// console.log(data);
// console.log('error');
}
});
}
As you can see, I've been playing with setting the contentType and using encodeURIComponent().
Any help would be appreciated.
Cheers

In order to avoid these encoding issues, don't use .val on the textarea that the tinyMCE instance is attached to. Instead, you can utilize tinyMCE's built-in getContent method like so:
tinyMCEInstance.getContent()

Related

When performing a replaceWith via Ajax, the html of the fields is not being replaced correctly

Before submitting with Ajax, I am changing the ids of all inputs on the form, due to a need.
The problem is when I submit using Ajax, I need to replace the html of all fields in the form using the replaceWith function, but it is not doing that. It is simply changing the html, but it seems to be keeping the original html when I inspect it in the browser.
HTML should be replaced as shown in image 2.
Why can't HTML be replaced correctly? Shouldn't the replaceWith function be used for such a situation?
var genericModal = getLastGenericModalObject();
var frmFormaContato = genericModal.find('.frm-create-edit');
var valdata = frmFormaContato.serialize();
$.ajax({
url: url,
type: "POST",
traditional: true,
data: valdata,
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
success: function (data) {
frmFormaContato.replaceWith(data);
stopLoadGlobal();
},
error: function (e) {
stopLoadGlobal();
redirectToError(e.status);
return false;
}
});
Thank you :)
The solution was to change the IDs before replacing the HTML according to the DOM.
var dataChanged = changeIds($(data));
frmFormaContato.replaceWith(dataChanged);

Why does the character "–" become a "?" after added to JSON string and posted to REST web service?

I have a web page with an edit form populated with data from the database.
I'm having problems with one character, an escaped n-dash character ... –
The input field looks like this ...
<input type="text" class="form-control" id="LocalName"
name="LocalName" value="–" />
(NOTE: The value is the string read from the database, then escaped using Apache Commons library like so ... StringEscapeUtils.escapeHtml4(sValue); ... if I don't escape it, it will display as value="?".)
When I click the 'Save' button, I put all the form data in a JSON string like this ...
$("#doSaveEntityButton").click(function() {
var formData = {
Name:$('#Name').val(),
Region:$('#Region').val(),
LocalName:$('#LocalName').val()
}
var sJSON = JSON.stringify(formData);
alert("001: sJSON = "+sJSON);
At this point, the text displayed in the alert looks like this ...
001: sJSON = {"Name":"Antarctica","Region":"Antarctica","LocalName":"?"}
Notice The LocalName value is a "?" character instead of the n-dash or even "–".
INTERESTING NOTE! I just noticed that when I copy and pasted this text from the alert dialog box to here, the character is displaying properly ... like so ...
001: sJSON = {"Name":"Antarctica","Region":"Antarctica","LocalName":"–"}
That's interesting, but I still have my problem.
My problem is ... I then POST the sJSON string version of formData to my web service like so ...
var sJSON = JSON.stringify(formData);
alert("001: sJSON = "+sJSON);
$.ajax({
type : "POST",
url : "/myapplication/json/saveentity",
data : sJSON,
contentType: "application/json; charset=utf-8",
dataType: "json",
success : function(msg) {
/* ... */
},
error : function(msg) {
displayMessages(msg.responseJSON.messages);
},
done : function(e) {
}
});
});
On the web service side, it appears as a "?" character. The n-dash has been lost.
My Java Spring MVC web service looks like this ...
#RequestMapping(value = "/json/app/{appId}/{entityDefId}/saveentity", method = RequestMethod.POST)
public ResponseEntity<String> saveEntity(#PathVariable("appId") int appId, #PathVariable("entityDefId") int entityDefId, #RequestBody String json) throws Exception {
Everything works fine with all of the other types of data.
What am I doing wrong with that n-dash?

How can I refresh a PHP file with itself using Ajax?

Alright guys I'm trying to make a filter system for posts using ajax and a select box. I am able to get the value from the select box no problem. But my issue is that when I try to include the selected value in my PHP file it doesn't do anything. I have a file called public_wall.php. This file contains PHP, Javascript, and HTML. How can I refresh this div whenever a user selects a different filter option? Basically I need the selected value to be passed onto my public_wall.php file and then I want to plug it into the PHP function that fetches the posts thats's in the same file and then I want to refresh that same file to display the filtered results. Here is my Javascript code.
$("#postRatings").on("click", function(e) {
selectedRatingFilter = $("#postRatings option:selected").val();
var dataString = "timeFilter="+selectedRatingFilter;
jQuery.ajax({
type: "POST",
url: site_url+"public_wall.php",
data: dataString,
dataType: "json",
cache: false,
success: function(response){
hideSpinner();
jQuery('#postsPagingDiv').remove();
jQuery('#wsc_midbox').html(jQuery(response.htmls).fadeIn(400));
setpost_ids(response.all_post_id);
jQuery('#paging_in_process').val(0);
}
});
});
When the dataType is set to "json" nothing happens. But when it is set to html it prints some javascript code. Please help. The PHP file is too large to include here, but it basically contains PHP, HTML, and Javascript and some PHP functions that do sql queries. What is the best way to achieve a filter mechanism for my setup?
And on the public_wall.php file I want to get the value like so:
$ratingFilter = isset($_REQUEST['timeFilter']) ? intval($_REQUEST['timeFilter']) : 0;
And then plug it into the PHP function that fetches the posts which is in the public_wall.php file also so that I can filter the posts based on the selected value. And then finally I want to refresh the public_wall.php file with the new results. I hope that makes sense. Please help.
This is the output when I set my dataType to "html"
<script>
function refreshPosts() {/* only posts comments likes and count updated. */
var posts = jQuery("#all_post_id").val();
var arrays = posts.split(',');
var dataString = "postids="+posts;
jQuery.ajax({
type: "POST",
url: site_url+"includes/update_wall.php",
data: dataString,
dataType: "json",
cache: false,
success: function(response) {
var x = response;
//############ skip posts whose comments are being read by users
var ExemptedPostsIDs = jQuery("#exemptedPostsID").val();
var ExemptedArray = ExemptedPostsIDs.split(',');
ExemptedArray = ExemptedArray.sort();
//////////////
for (i=0; i<arrays.length; i++) {
var val = 'row'+arrays[i];
if(x[val]) {
if(!inArray(arrays[i], ExemptedArray))
jQuery("#ajax_wall_"+arrays[i]).html(x[val]);
} else {
jQuery('#PostBoxID'+arrays[i]).parent().fadeOut(500);
}
}
}
});
}
function inArray(needle, haystack) {
var length = haystack.length;
for (var i = 0; i < length; i++) {
if(haystack[i] == needle) return true;
}
return false;
}
function refreshWall() {/* loads new posts real time */
var posts = jQuery("#all_post_id").val();
var pageUsing = jQuery('#pageUsing').val();
var dataString = "update_posts=1&postids="+posts+'&pagex='+pageUsing;
jQuery.ajax({
type: "POST",
url: site_url+"public_wall.php",
data: dataString,
dataType: "json",
cache: false,
success: function(response) {
if(response.all_post_id) {
jQuery('#wsc_midbox').prepend(jQuery(response.htmls).fadeIn(400));
setpost_ids(response.all_post_id);
}
}
});
}
</script>
I suggest you keep the form with select element and any JavaScript on the outer frame.
Via ajax, only load the results to a seperate DIVision below that.
When you put an Ajax response to a div, any JavaScript inside it will not be executed.
For the best throughput with Ajax, you should consider loading a json response via Ajax and create HTML elements on the client side. That way it becomes much easier to pull additional variables to front-end JS from server side along with the same request/response.
But that becomes bit difficult when you have a template engine in the back-end. You can still send the HTML content in a json value, so you can easily pass the "all_post_id" as well..

Javascript value cuts off after '&' character

So I'm relatively new with Javascript and Ajax, and using them to submit data to the database for live updating, but I'm noticing that when there is a '&' character entered into my input/textareas, when I gets the value, it cuts the string off after the '&'.
I've tested the value by using the alert function after the lines of code below, and the full string is there, but not exactly sure how to fix this.
I tried to replace the '&' character with & but can't get it to work. Here is what I used to get the values and the replace I tried to use. Note: I'm using the nicEditor and have to use the first line of the code to get the text from the proper field that stores the text inside the editor.
var boxval = $('#statusContentForum').find('.nicEdit-main').text();
var dataString = 'statusContent='+ boxval;
var dataString = dataString.replace(/&/g, '&');
var dataString = dataString.replace(/\|&;\$%#"<>\(\)\+,/g, "");
and used these characters to test it.
abcdefghijklmnopqrstuvwxyz 1234567890-=`~!##$%^&*()_+{}[]|\"':;,<.>?/
but it only results in this
abcdefghijklmnopqrstuvwxyz 1234567890-=`~!##$%^
Have any of you encountered this before? I'd appreciate any help, and if you need more code let me know. I can provide it.
*********UPDAT FULL CODE *********
Here is the full code.
The JS/AJAX:
$(function() {
//Update Message...
$(".update_button").click(function() {
//var boxval = $("#statusContent").val();
var boxval = $('#statusContentForum').find('.nicEdit-main').text();
var dataString = 'statusContent='+ boxval;
//var dataString = dataString.replace(/>/g, '>');
//var dataString = dataString.replace(/</g, '<');
var dataString = dataString.replace(/&/g, '&');
var dataString = dataString.replace(/\|&;\$%#"<>\(\)\+,/g, "");
if(boxval=='') {
alert("Please Enter Some Text");
} else {
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="images/ajax-loader.gif" align="absmiddle"> <span class="loading">Loading Comment...</span>');
// alert(dataString);
// throw new Error("Something went badly wrong!");
$.ajax({
type: "POST",
url: "ajax/statusPost.php",
data: dataString,
cache: false,
success: function(html){
$("ol#update").prepend(html);
$("ol#update li").slideDown("slow");
var clearVal = nicEditors.findEditor("statusContent");
clearVal.setContent("");
$("#flash").hide();
}
});
} return false;
});
});
The HTML if you need it.
<form name="newstatus" id="statusContentForum" action="profile.php" method="post" class="commentForm">
<textarea name="statusContent" id="statusContent" placeholder="What's on your mind?"></textarea>
<input type="submit" value="Update" name="submit" class="update_button"/>
</form>
You are manually constructing an application/x-www-form-urlencoded string, but aren't encoding & correctly. To represent a & as data in that format you need to replace it with %26.
The encodeURIComponent function will do this for you.
However, you are using jQuery so you shouldn't do it manually at all. Pass data an object instead of a string.
data: {
statusContent: boxval
},
I'm assuming you're familiar with other programming languages, and perhaps even key words or sensitive characters. Always remember to look into that as a first solution to your issue. In this case, that's what was going on. If you encode the string for that variable you're setting it should work just fine.
Try console logging it.
console.log(encodeURIComponent('My Var: ' + dataString));
See here for more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

Javascript get current page html (after editing)

I have a page that I have edited after load and what I want to do is get the pages current HTML and pass that off to a PHP script.
I first passed document.documentElement.innerHTML but that ended up including a bunch of computed style garbage at the top which I did not want. After googling around I found I could use ajax to get a copy of the current file on the server and then replace the edited part afterwards.
I can get the copy of the file using this:
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
$.ajax({
url: filename,
async: false, // asynchronous request? (synchronous requests are discouraged...)
cache: false, // with this, you can force the browser to not make cache of the retrieved data
dataType: "text", // jQuery will infer this, but you can set explicitly
success: function( data, textStatus, jqXHR ) {
origPage = data; // can be a global variable too...
// process the content...
}
});
Which works fine and gets me the html I expected and see when viewing the page in notepad.
The next step is what I cannot figure out. All I want to do is swap out the innerHTML of a div with an id of 'editor' with what the current value is, so I have tried this:
origPage.getElementById('editor').innerHTML = e.html;
But I get the error "TypeError: undefined is not a function". I must be doing something simple wrong I feel but I don't know the proper formatting to do this. I have tried the following variations:
alert($(origPage).getElementById('editor').innerHTML);
//Different attempt
var newHtml = $.parseHTML( origPage );
alert($(newHtml).getElementById('editor').innerHTML);
//Different attempt
alert($(origPage).html().getElementById('editor').innerHTML);
But I always get "TypeError: undefined is not a function" or "TypeError: Cannot read property 'getElementById' of undefined". How can I do this properly?
EDIT:
Complete page html below:
<!DOCTYPE html>
<html>
<body>
<div id="editor">
<h1>This is editable.</h1>
<p>Click me to start editing.</p>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript" src="snapeditor.js"></script>
<script type="text/javascript">
var editor = new SnapEditor.InPlace("editor", {onSave: function (e) {
var isSuccess = true;
//var origPage = e.html;
var origPage;
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
// Actually perform the save and update isSuccess.
// Javascript:
$.ajax({
url: filename,
async: false, // asynchronous request? (synchronous requests are discouraged...)
cache: false, // with this, you can force the browser to not make cache of the retrieved data
dataType: "text", // jQuery will infer this, but you can set explicitly
success: function( data, textStatus, jqXHR ) {
origPage = data; // can be a global variable too...
// process the content...
}
});
//origPage shows expected html as this point
//alert($(origPage).getElementById('editor').innerHTML);
//alert($(origPage).html().getElementById('editor').innerHTML);
$(origPage).getElementById('editor').innerHTML = e.html;//fails here
alert(origPage);
//alert(newHtml.getElementById('editor').innerHTML);
$.ajax({
data: {html: origPage, docName: 'example1.html'},
url: 'savePage.php',
method: 'POST', // or GET
success: function(msg) {
alert(msg);
isSuccess = true;
}
});
return isSuccess || "Error";
},
onUnsavedChanges: function (e) {
if(confirm("Save changes?")) {
if(e.api.execAction("save")){
//location.reload();
}
} else {
e.api.execAction("discard");
}
}});
</script>
</body>
</html>
It seems that you get the user's changes in a variable - you called the var e.html. That is not a good variable name, BTW. If you can, change it to something like htmlEdited
Question: If you add the command alert(e.html); what do you get? Do you see the HTML after user edits?
If yes, then what you need to do is send that variable to a PHP file, which will receive the data and stick it into the database.
Code to send the data:
javascript/jQuery:
alert(e.html); //you should see the user-edited HTML
$.ajax({
type: 'post',
url: 'another_php_file.php',
data: 'userStuff=' + e.html, //var_name = var_contents
success: function(d){
window.location.href = ''; //redisplay this page
}
});
another_php_file.php:
<?php
$user_edits = $_POST['userStuff']; //note exact same name as data statement above
mysql_query("UPDATE `your_table_name` SET `your_col_name` = '$user_edits' ") or die(mysql_error());
echo 'All donarino';
The AJAX javascript code will send the var contents to a PHP file called another_php_file.php.
The data is received as $user_edits, and then inserted into your MySQL db
Finally, I presume that if you redisplay that page it will once again grab the contents of the #editor div from the database?
This is where you haven't provided enough information, and why I wanted to see all your code.
ARE you populating that div from the database? If not, then how do you expect the page to be updated after refreshing the page?
You would benefit from doing some tutorials at phpacademy.org or a thenewboston.com. Do these two (free) courses and you'll be an expert:
https://phpacademy.org/videos/php-and-mysql-with-mysqli
https://phpacademy.org/videos/oop-loginregister-system
If all you need to do is insert the contents of e.html to replace the #editor div, then try this:
$('#editor').html(e.html);
HOWEVER, you need an event to trigger that code. Are you able to do this?
alert(e.html);
If so, then put the first bit of code at that same spot. If not, we need more information about when your code receives that variable -- that is where you put the $('#editor').html(e.html); statement.

Categories

Resources