Javascript value cuts off after '&' character - javascript

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

Related

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?

AJAX POST of tinyMCE contents - Character encoding of table entities

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()

Parsing duplicate xml child elements with javascript

So I've been able to apply some code online from previous discussions to a project that I'm working on however, now that there are multiple xml elements to grab I cannot seem to figure out how.
The xml structure is set up like this:
``
<DEPTId id = "1234">
<GROUP_DESCRIPTION>Something</GROUP_DESCRIPTION>
<DESCIPTION>Some department</DESCRIPTION>
<SOFTWARE>piece 1<SOFTWARE>
<SOFTWARE>DSFAON</SOFTWARE>
<SOFTWARE>asdvn</SOFTWARE>
<DEPTId>
I have tried to either reformat the structure to be SOFTWARE1, SOFTWARE2, .. but I felt as though one element should suffice as there can be many pieces of software, and couldn't find a way to iterate across each element. However the code I have only prints out the SOFTWARE elements text as one string, and not separate checkboxes which I want.
My JavaScript is below. It checks their group and department from the html page, and if it is equal to the xml it will append the listed software to the table on the page.
function defaultSoftware() {
$("#defaultSoftwareList").empty();
$.ajax({
type: "GET",
url: "blahblah.xml",
contentType: "charset=utf-8",
dataType: "xml",
async: true,
success: parsePersonaXML
});
function parsePersonaXML(xml) {
$(xml).find("DEPTId").each(function() {
var htmlDepartment = $("#b1Department").val();
var htmlGroup = $("#techpersonaGroup").val();
var xmlGroup = $(this).find("GROUP_DESCRIPTION").text();
var xmlDepartment = $(this).find("DESCRIPTION").text();
if (htmlDepartment == xmlDepartment && htmlGroup == xmlGroup)
$(this).find("SOFTWARE").each(function() {
var sd = ("SOFTWARE").text();
$("#techpersonaList").append('<input type="checkbox" checked /> ' + sd + '<br />');
});
});
}
}
If anyone knows what I am doing wrong or how I can change it your help would be much appreciated!

ajax field insert without loading second page bug

So I went through this tutorial http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/ and instead of using php I created my own classic asp page, but one thing is bugging me when trying to put spaces in the input boxes they do not show up for example if I put bill gates in the name field it shows up as billgates
any ideas
$(".btn22").bind("click", function() {
var name = $("input#yourname").val();
if (name === "") {
$("input#yourname").focus();
return false;
}
var email = $("input#youremail").val();
if (email === "") {
$("input#youremail").focus();
return false;
}
var message5 = $("#limitedtextarea").text();
if (message5 === "") {
$("#limitedtextarea").focus();
return false;
}
var sku5 = $("#sku5").val();
var dataString = 'yourname='+ name + '&youremail=' + email + '&message=' + message5 + '&sku5=' + sku5;
$.ajax({
type: "POST",
url: "actions/newreview.asp",
data: dataString,
success: function() {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<br><br><p class='big red'>Thanks for the review.</p>")
.hide()
.fadeIn(1500, function() {
$('#message');
});
}
});
return false;
});
});
'asp looks like this
name = request.form("yourname")
email = request.form("youremail")
sku = request.form("sku5")
comment = request.form("message")
then inserts names into a database, but it has already gotten rid of the spaces before this point
You'll have to post your markup here for us to tell what's going on for sure, but have you set the input type to type='text'?
looks like you are doing your own encoding of the form data. Not sure if that's the problem but it could be. jQuery includes a utility that does this for you.
dataString = $("#JqAjaxForm").serialize();
reference: http://api.jquery.com/serialize/
Some other comments:
you may wish to produce a javascript object, rather than just use form encoding. In this case jQuery will serialize it into json, if you use dataType:json on the post() method.
use Javascript in your classic ASP page. It may make things a little simpler for you, to use the same language on client (browser) and server.
figured it out just added name = escape(name) add the %20 in and then take it out to add spaces in my asp code
thanks everyone

get form data with javascript and then submit it to a php file using ajax

I am having some trouble working out how to get data from a form to post via ajax. I have the following code but it doesn't seem to be sending though the data from elements like checkboxes and radio buttons. Instead it is sending though all the fields. ie if there is a set of radiobuttons it is sending through all the possibilities not just the checked ones. The form can be made up of any type of element and have an undermined amount of elements in it, so I need to iterate through in the way I am. That part seems to be working, but I can't seem to get the javascript to grab the selected data. Do I need to manually check each element's type and then check to see if it checked etc?
myString = "";
my_form_id = "1";
my_url = "phpscript.php";
elem = document.getElementById("form_" + my_form_id).elements;
for(var i = 0; i < elem.length; i++)
{
if (i>0) { myString += "&"; }
myString += elem[i].name + "=" + elem[i].value;
}
$.ajax({
type: "POST",
url: my_url,
data: myString,
success: function(data) {
// process the post data
}
});
`
Since you're using jQuery, you can drastically simplify it all:
var my_form_id = "1";
var my_url = "phpscript.php";
var form = $("#form_" + my_form_id);
$.ajax({
type: "POST",
url: my_url,
data: form.serialize(),
success: function(data) {
// process the post data
}
});
jQuery's serialize method does all the work for you. But if you wanted to do it by hand, then yes, you would have to check each field.

Categories

Resources