I'm reading the value of an input text field and passing it to be used as ajax data
The field value has a +
<input name="someval" type="text" value="Receive (+ open)" />
and looks like when parsed with data, it parses the + as a jquery concatenation.
data: 'someval=' + $("input[name=someval]").val(),
This is the first time I notice this behavior.
First, how do I solve it.
Second, I have no way of knowing when the output might have these special chars, so is there a known best practice way to escape input so that whenever it happens we're covered?
Thanks
Try encodeURIComponent:
'someval=' + encodeURIComponent($("input[name=someval]").val())
Better yet, let jQuery handle it for you:
data: { someval:$("input[name=someval]").val() }
jQuery will automatically escape your values (and keys) into the correct format (using jQuery.param()) for the data type (eg "application/x-www-form-urlencoded").
Related
I have a html page in which I need to pass a String variable to javascript function. This works until String does not have a special charecter.
<html>
<head>
<script>
function test(v){
alert(v);
}
</script>
</head>
<body>
<input type="button" value="Test Button" onClick="test('BlahBlah')"/>
</body>
</html>
As soon as I change onClick like below, it stops working.
onClick="test('Blah'Blah')"
Any solution for this problem. Please take a note parameter which is being passed to JavaScript function is dynamic.Source of Parameter is backend and I cannot change that peice of code. Second thing even if put escape it still does not work. My problem is I have to retian the special charecter for some processing at backend
There are two layers to this:
The content of onClick attributes, like all attributes, is HTML text. That means that any character that's special in HTML (like <) must be replaced with an HTML entity (e.g., <). Additionally, if you use double quotes around the attribute value, any double quotes within the value must be replaced with entities ("); if you used single quotes around the attribute, you'd need to replace ' with '.
Your attribute contains a JavaScript string literal. That means that any characters that are special inside JavaScript string literals must be escaped according to the JavaScript rules. Since you've used single quotes to delimit the JavaScript string, for instance, you have to escape any single quotes in the string with a backslash.
I'm assuming that HTML is generated server-side. If so, the work above must be done server-side, when building the HTML of the page. You haven't said what server-side tech you're using, so it's hard to point you at solutions that your server-side tech/environment might provide.
In the simple case of your
onClick="test('Blah'Blah')"
...you just need to add the backslash within the JavaScript string
onClick="test('Blah\'Blah')"
...but that's just that one specific case.
The dramatically simpler option is to not put JavaScript code in attribute values. Instead, use modern techniques (addEventListener, attachEvent) to hook up JavaScript code.
But if you must use an onClick attribute, avoid having text in it (or deal with the complexities above); have it call a function defined in a script element that then has the text, as you then have only the one layer (#2 above) to deal with.
Source of Parameter is backend and I cannot change that peice of code.
That backend is broken and needs fixing.
If:
the backend is only producing invalid JavaScript code (not invalid HTML)
and the code consists of a single function call
and the code is always a single function call
and the function call always has a single string literal argument
and that argument is always delimited with single quotes
and the single quotes within the string are never correctly escaped
...we might be able to salvage it client-side. But my guess is that the backend will also produce invalid HTML, for instance when the text has a " in it. (We can't do anything about that, because the attribute value will be chopped off at that point.)
But let's keep a good thought: Given the ridiculous list of caveats above, this might do it:
var elm = document.getElementById("the-div");
var code = elm.getAttribute("onclick");
var m = code.match(/^([^(]+)\('(.*)'\)$/);
if (m) {
code = m[1] + "('" + m[2].replace(/'/g, "\\'") + "')";
}
elm.setAttribute("onclick", code);
Live Example:
function foo(str) {
alert(str);
}
var elm = document.getElementById("the-div");
var code = elm.getAttribute("onclick");
var m = code.match(/^([^(]+)\('(.*)'\)$/);
if (m) {
code = m[1] + "('" + m[2].replace(/'/g, "\\'") + "')";
}
elm.setAttribute("onclick", code);
<div id="the-div" onclick="foo('blah'blah')">Click me</div>
Well this is an very common problem you wanted to add single quotes inside single quotes to do this you have to escape that Sigle quotes to do that you have to put an forward slash.
onClick="test('Blah\'Blah')"
In this case, I suppose explaining the problem as a scenario would be the best way to explain it.
I have a search box in a page called A.html, parameters that are passed to this page should be replaced with the value of its search box. The problem is that, when I pass the parameters the spaces get replaced by %2520 therefore wrong value will be added to the search box. I need to solve it.
Link
Following address will be put into the address bar: www.example.com/a.html?value=Here%2520and%2520there
This value will be replaced with the value of the search box: Here%2520and%2520there. I need to have this value "Here and There" in my search box. (without %2520)
What seems to have happened here is that the URL was double encoded (see below); while I can't explain exactly why that happens, it may be because your URL is not properly URL encoded:
Link
It should be:
Link
Or:
Link
Double encoding goes like this:
" " regular space
"%20" percent encoded, " " -> "%20"
"%2520" percent encoded, "%" -> "%25"
Update
The reason I couldn't explain the double encoding is because the question was missing exactly how the passed value was added to the search box. The most likely scenario is that the search box is populated with a percent encoded value. To fix that, you have to decode the value first, i.e.
searchBox.value = decodeURIComponent('Here%20and%20there');
See also: decodeURIComponent()
As has been mentioned, serving this data as a URL requires spaces and other non-ascii characters to be URL encoded. Without this, the browser would not be able to properly parse the URI.
You can make changes to solicit the raw data without encoding it (keep spaces intact), but this will be of no use if you are appending to a URL. If you aren't, feel free to paste the code relating to whatever you are trying to do with the data.
I am having a problem with special character in javascript.
I have a form with a input text that has the following string:
10/10/2010
after a form.serialize(); I get this string as
10%2F10%2F2010
The '/' character is converted to its ASCII code %2F.
I would be able to convert that using String.fromCharCode(ascii_code) but I have many inputs in my form so these string is somenthing like:
var=14&var=10%2F10%2F2010&var=10%2F10%2F2010&var=10%2F10%2F2010
Just an example to state that I would have to go through this string ("manually") and find those value and convert it.
Is there any easy way to perform that conversion?
Strange thing because I did not have that problem before, I am not sure why this is happening now.
I happens that way because that's how it's meant to be:
The .serialize() method creates a text string in standard URL-encoded
notation. It operates on a jQuery object representing a set of form
elements.
As far as I know, there's no native jQuery function to unserialize but your post suggests you already got that and are only stuck in the URL-encoded strings:
decodeURIComponent(encodedURI)Decodes a Uniform Resource Identifier (URI) component previously created by encodeURIComponent or
by a similar routine.
I have a grid with link button and on RowDatabound:
lbutton.Attributes.Add("onclick",
"javascript:window.showModalDialog('Showsome.aspx?ID=" + lbutton.CommandArgument + " &IsMA=M" +
"','window.self','dialogWidth:800px; dialogHeight:800px;center:yes; status:yes; scroll:no; help:no');");
I am able to retrieve ID from Request.QueryString["ID"];
However, I am not able to retrieve Request.QueryString["IsMA"]
How can this be achieved?
I tried the suggestions, no more spaces and did URL encode and I am not getting the value correctly. I have another approach since it is a hardcoded value 'M' that is needed along with the value I am now appending it in ID value itself 'Showsome.aspx?ID=M" . Thanks for you support.
Theres a space between the CommandArgument and &IsMA
Could this be causing your problem?
Try:
+ lbutton.CommandArgument + "&IsMA=M"
What is CommandArgument value? You may need to encode this. I would recommend doing this either way.
+ Server.UrlEncode(lbutton.CommandArgument) + "&IsMA=M"
Try removing the space before the ampersand character:
lbutton.CommandArgument + "&IsMA=M"
EDIT: As SLaks points out below, escaping the ampersand character is not necessary. Accordingly, the documentation for Attributes.Add() says:
If the string in the value parameter contains an ampersand (&), the
character is automatically encoded. The resulting HTML representation
is "&".
I have an issue with submitting post data. I have a form which have a couple of text fields in, and when a button is pressed to submit the data, it is run through a custom from validation (JS), then I construct a query string like
title=test&content=some content
which is then submitted to the server. The problem I had is when I have '&' (eg  ) entered into one of the inputs which then breaks up the query string. Eg:
title=test&content=some content  
How do I get around this?
Thanks in advance,
Harry.
Run encodeURIComponent over each key and value.
var title = "test";
var content = "some content   ";
var data = encodeURIComponent('title') + /* You don't actually need to encode this as it is a string that only contains safe characters, but you would if you weren't sure about the data */
'=' + encodeURIComponent(title) +
'&' + encodeURIComponent('content') +
'=' + encodeURIComponent(content);
Encode the string..when you want to encode a query string with special characters you need to use encoding. ampersand is encoded like this
title=test&content=some content %26
basically any character in a query string can be replaced by its ASCII Hex equivalent with a % as the prefix
Space = %20
A = %41
B = %42
C = %43
...
You need to encode your query to make it URL-safe. You can refer to the following links on how to do that in JS:
http://xkr.us/articles/javascript/encode-compare/
http://www.webtoolkit.info/javascript-url-decode-encode.html
You said:
...and when a button is pressed to submit the data, it is run through a custom from validation (JS), then I construct a query string...
In the section where you are building the query string you should also run the value of each input through encodeURIComponent() as David Dorward suggested.
As you do - be careful that you only assign the new value to your processed query string and NOT the form element value, otherwise your users will think their input was somehow corrupted and potentially freak out.
[EDIT]
I just re-read your question and realized something important: you're encoding an   ;character. This is probably a more complicated issue than other posters here have read into. If you want that character, and other &code; type characters to transfer over you'll need to realize that they are codes. Those characters &, n, b, s, p and ; are not themselves the same as " " which is a space character that does not break.
You'll have to add another step of encoding/decoding. You can place this step either before of after the data is sent (or "POSTed").
Before:
(Using this question's answers)
var data = formElement.value;
data = rhtmlspecialchars(data, 0);
Which is intended to replace your "special" characters like with " " so that they are then properly encoded by encodeURIComponent(data)
Or after:
(using standard PHP functions)
<?PHP
$your_field_name = htmlspecialchars_decode(urldecode($_POST['your_field_name']));
?>
This assumes that you escaped the & in your POST with %26
If you replaced it with some function other than encodeURIComponent() you'll have to find a different way to decode it in PHP.
This should solve your problem:
encodeURIComponent(name)+'='+encodeURIComponent(value)+'&'+encodeURIComponent(name2)+'='+encodeURIComponent(value2)
You need to escape each value (and name if you want to be on the safe side) before concatenating them when you're building your query.
The JavaScript global function encodeURIComponent() does the escaping.
The global function escape() (DOM) does this for you in a browser. Although people are saying it is not doing the escaping well for unicode chars. Anyway if you're only concerned about '&' then this would solve your problem.