JS - Submit parameter's value with "&" - javascript

I´m working with a .js referring to a form.
In a function it sets the form's action and then submit it.
document.forms[0].action = "FileController.do?action=genFile&fileType="+ft+"&answType="+at;
document.forms[0].submit();
The problem is that answType's value sometimes has an "&" on it, like "M&M", so when I try to get that value like this:
String answer = request.getParameter("answType");
I only get the first "M" and lost the rest of the value.
I know that's because parameters are separated by "&".
But is there a workaround for this?
I can't change the original data.
Thank's

encodeURIComponent(string) will convert characters with special meaning in URLs (such as &) to their escape sequences.

Related

JSON parse gives error occasionally on parsing string

I have same input fields where the user inputs some data. Next my code converts it to JSON and send it to the server.
$("#submit").click(function(){
var inp = $("#inpTxt").val();
if(inp == null || inp == ""){
return;
}
jsonResult = JSON.parse('{"data": "' + inp + '"}');
$.ajax({
data : jsonResult,
...
});
});
The issue here is that sometimes the above code works and sometimes it just don't.
Most of the time I tested the code it worked like a charm but on productions I keep on getting the error reported several times.
I have not been able to figure out the possible cause yet.
Note: Some parts of the code are not shared in above but only part of what the problem seems to be.
As per the last comment the problem seems to be occurring when someone inputs some escape character in input (#Noob46 identified the case of using "Something" case but in my opinion it will also occur if any other escape character like \ or any other starting with \ may also cause the same problem).
Thus, one way to handle this is to filter the coming input string before passing it to JSON.parse.
To take things a step forward I have created some js that you can find here which in fact will let you handle the escape characters if they come as part of your input.
For further details refer to the attached code and example in the provided link here.
As the problem identified by me so let me also state an answer here. All you need is to add an additional \ before all the escape characters you encounter like:
\b : backspace
\f : form feed
\n : line feed
\r : carriage return
\t : horizontal tab
\v : vertical tab
" : double quote
\ : back slash
You can do so by code like:
inp = inp.replace('"','\\\"');
Or inp.replace('\','\\\\');
And so on for other characters.
When you use JSON.Parse function you need to handle special characters by your self. So if someone puts a " in your inpTxt input it will cause an error on parse that string.
You should do something like the code below to avoid parse error and let javascript correctly handle special characters on your string.
jsonResult = { data: inp };
I create a JS fiddle to make it easier to understand.
https://jsfiddle.net/ub3w0a8x/

unescape in javascript not working when %26 ( & sign) is in value

I have the below code in my JSP. UI displays every character correctly other than "&".
<c:out value="<script>var escapedData=unescape('${column}');
$('div').html(escapedData);</script>" escapeXml="false" /> </div>
E.g. 1) working case
input = ni!er#
Value in my escapedData variable is ni%21er%40. Now when I put it in my div using
$('div').html(escapedData); then o/p on html is as expected
E.g. 2) Issue case
input = nice&
Value in my escapedData variable is nice%26. Now when I put it in my div using
$('div').html(escapedData); then also it displays below
$('#test20').html('nice%26');
However, when output is displayed in JSP, it just prints "nice". It truncates everything after &.
Any suggestions?
It looks like you have some misunderstandings what unescape(val)/escape(val) do and where you need them. And what you need to take attention of when you use .html().
HTML and URI have certain character that have special meanings. The most important ones are:
HTML: <, >, &
URI: /,?,%,&
If you want to use one of those characters in HTML or URI you need to escape them.
The escaping for URI and for HTML are different.
The functions unescape/escape (deprecated) and decodeURI/endcodeURI are for URI. But was you want is to escape your data into the HTML format.
There is no build-in function in_JS_ that does this but you could e.g. use the code of the answer to this question Can I escape html special chars in javascript?.
But as it seems that you use jQuery you could think of just using .text instead of .html as this will do the escaping for you.
An additional note:
I'm pretty sure that the var escapedData=unescape('${column}'); does not do anything. I assume that ${column} already is ni!er#/nice&.
So please check your source code. If var escapedData=unescape('${column}'); will look like var escapedData=unescape('ni!er#'); then you should remove the unescape otherwise you would not get the expected result if the ${column} contains something like e.g. %23.

Filepath and it's URL variable is cut short when concatenated

I have the following JQuery AJAX function:
function JQueryAJAXFunction(){
$input = document.getElementById("textInput").value;
console.log($input ); //Console output: "How to"
$('#resultsOutput').load('ajax/serverside/filepath.php?urlvariable='+$input);
}
It retrieves the value of $input from text field, which is a two letter word such as "How to" and displays it on the browser's console.
$input is then concatenated with the file path for the server side script and is assigned as a URL variable. However, in doing so the last word of $input -in this case "to"- disappears/is cut off.
Once the function is executed, the URL variable on the server is retrieved and displayed using for example: $_GET["urlvariable"] It's value is as you can guess "How".
What is the recommended solution to the problem? How can I get $_GET["urlvariable"] be equal to "How to".
Certain characters need to be encoded when used in URLs...a space is one of them. JavaScript provides a global function to encode any necessary characters for URLs - encodeURIComponent. Instead of just concatenating $input, you would concatenate:
encodeURIComponent($input)
Reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

Single Quote in Javascript Param

I have a function that, when clicked, fills in a field of the parent window. In this case, it's a name (text) field.
The problem I'm having is if the field has a single quote in it (ex. Bill's Chili) the function fails because it reads the single quote as the end of the parameter.
Here is the call:
href="javascript:selectItem('recipe','recipe_name','<recipe_description')"
Again, if the name is Bill's Chili, it causes a syntax error.
Is there a way to automatically convert that single quote to the HTML equivalent so it will read properly?
Thanks
For the single quotes in the field use \' More info on escape characters here.
href="javascript:selectItem('Bill\'s Chilli','recipe_name','<recipe_description')"
The answer I found was completely different than I thought. The page itself is written is ASP (Sorry I forgot to mention that, I didn't think it mattered since the function was javascript and it was called in HTML).
Therefore, I just used this:
<%fixed_name = Replace(recipe_name,"'","") %>
And then used fixed_name instead of recipe_name in the function call.
Thanks for all your help, it set me in the right direction!
try this
href='javascript:selectItem("recipe","recipe_name","<recipe_description")'
You may try to use escaped 'double' quote like that:
href="javascript:selectItem(\"recipe\",\"recipe_name\",\"recipe_description\")"
Please let me know whether it works.
You could use str.replace
Just remplace " by " et ' by ' . :)
But actually, I'm assuming you're getting all of that stuff from a php script (from some sort of storage), in which case you could escape the quotes directly with php, that would be way more safer.

How to get a Clean String in Javascript?

i have a long String. With some German characters and lots of new lines tabs ect..
In a Selectbox user can select a text, on change i do
document.getElementById('text').value=this.value;
But this fails. I just get a "unterminated string literal" as error in JavaScript.
I think i should clean the string.
How can i do it in JavaScript?
Its not because of that code, there is syntax error somewhere in your javascript file.
For example, in one of your previous question's answer
alert("yes link clicked);
You could see, there is " is missing after clicked, which could cause unterminated string literal error. Fix it like
alert("yes link clicked");
As I cannot judge from your code, you might want to check what this in this.value refers to, e.g. using an alert("debug: " + this.value) .
Other than that, you might want to use encodeURI() for converting umlauts and other special characters to hexadecimal notation. If your page's content-type is set to UTF-8 special characters will then display correctly.

Categories