handling ampersand (&) in input using js [duplicate] - javascript

This question already has answers here:
How can I send the "&" (ampersand) character via AJAX?
(8 answers)
Closed 7 years ago.
This has been asked before but mine is different. I cant rub my head around this. I have a wysiwyg form that is being fetched by jquery and saved by ajax
var content=$('.inputfield').val();
fields='front='+fcarddetails;
$.ajax({
method:'POST',
url:actionpage,
data:fields,
beforeSend:function()
{
$("#processing").show();
},
complete:function ()
{
$("#processing").hide();
},
success: function(feedback)
{
} etc.
When '&' is added to the field, the whole input is messed up.
I a have handled all the html escapes, filters and special characters. But the code gets broken even before it reaches php action page. I cant convert '&' to & because it still contains '&'. Please help, problem is in js, not php but you can prove me otherwise. Thanks in advance.

Encode the string using encodeURIComponent.
The encodeURIComponent() method encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).
var fcarddetails = 'Tom&Jerry';
fields = 'front=' + encodeURIComponent(fcarddetails);
document.write(fields);

Related

php json_encode different output than js JSON.stringify [duplicate]

This question already has an answer here:
Reference: Why are my "special" Unicode characters encoded weird using json_encode?
(1 answer)
Closed 3 years ago.
I get two different results for
json_encode([ 'name' => 'xxx❤xxx' ]);
--> {"name":"xxx\u2764xxx"}
JSON.stringify({ name: 'xxx❤xxx');
--> {"name":"xxx❤xxx"}
Why is that and how can I make sure that the js version produces the same result as the php version?
The escaping in PHP is optional but not technically required for valid JSON (which can contain arbitrary Unicode aside from a few reserved whitespace characters). The feature can be turned off with json_encode($data, JSON_UNESCAPED_UNICODE).
Unfortunately, the JS version doesn't have the feature at all. If you want to escape multibyte characters to \u...., you should do it explicitly; see JSON.stringify and unicode characters.

Symbols inside values breaking if statements in PHP [duplicate]

This question already has answers here:
AJAX POST and Plus Sign ( + ) -- How to Encode?
(6 answers)
Closed 5 years ago.
I have a web app where if someone selects something in the dropdown menu, it changes the next field with Ajax. I'm having difficulty when the values of the dropdown have a '+' symbol which breaks it.
For example this works:
if ($_GET['ch'] == 'Something here - here') {}
However this does not
if ($_GET['ch'] == 'Something here + here') {}
I'd like a solution to be able to include the + symbol inside. Some symbols seem to work fine including brackets (), dashes -, etc.
Try encodeURI function, and/or use POST instead.
Also escaping characters would be good. (like \+ instead of +)
When you are escaping characters than at php side you should use stripslashes function if you need special characters.

Encode special characters to pass in url and read by javascript [duplicate]

This question already has answers here:
Encode URL in JavaScript
(22 answers)
Closed 8 years ago.
I need to pass some parameters in the url and they can have special characters like ", spanish Ñ or ñ, : spaces and accents.
What is the propper way to encode them before adding to the url or in case I got in the html like that, read them?
I tried this:
arrayData[i] = pair[1].replace('+', " ").replace('%22', "\"");
But just get working with + or spaces, not both at the same time or in 2 lines:
arrayData[i] = pair[1].replace('+', " ");
arrayData[i] = pair[i].replace('%22', "\"");
You can try encodeUri Built-in function, for example
encodeURI('coño funcionó!')
Previous answer is correct. JavaScript has built in functions for fulfilling this kind of tasks.
You can try to investigate these functions in w3schools.com. Here are the links with basic information and live "Try it out" feature:
encodeURI - takes string with your characters and encodes it into plausible for url style ( encoding spaces and non ANSII chars )
decodeURI - takes encoded string and decodes it to initial state

POST data issues

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 &nbsp) entered into one of the inputs which then breaks up the query string. Eg:
title=test&content=some content &nbsp
How do I get around this?
Thanks in advance,
Harry.
Run encodeURIComponent over each key and value.
var title = "test";
var content = "some content &nbsp ";
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 &nbsp ;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.

Character/URI encoding in JavaScript getting out of sync?

I have a question about encoding special/extended UTF-8 characters in URLs in JavaScript. The same question applies to many characters like the Registered R-circle, but my example uses an umlaut:
ü = %C3%BC in UTF-8 (four rows from bottom of http://www.utf8-chartable.de/)
If the url contains an umlaut represented as UTF-8 (ü = %C3%BC), and I run it through encodeURIComponent, the %s are encode, the string now looks like "%25C3%25BC" and it gets correctly processed by my system. This is good.
url = "http://foo.com/bar.html?%C3%BC"
url = encodeURIComponent(url);
// url is now represented as "http%3A%2F%2Ffoo.com%2Fbar.html%3F%25C3%25BC"
However, the bad: If the pre-encoded string has an unencoded character, the actual umlaut, the after encoding is looks like "%C3%BC" and fails because, I believe, the %s should be encoded, too.:
url = "http://foo.com/bar.html?ü"
url = encodeURIComponent(url);
// url is now represented as "http%3A%2F%2Ffoo.com%2Fbar.html%3F%C3%BC"
I think it fails because it is less thoroughly encoded than the rest of the url.
So, beyond general advice or answers to questions I don't know to ask, what I think i want to know is how to get the raw umlaut (and all other special characters) to fully encode. Is that what is incorrect?
Thanks for your help!
Nate
You cannot encode a URL all at once. If you have already concatenated the host, path, parameters, etc., together then it's impossible to correctly determine which characters actually need to be encoded and which characters are separators that need to be left alone.
The only reliable way to build a URL is by concatenating already-encoded values:
"http://foo.com/bar.html?" + encodeURIComponent("%C3%BC")

Categories

Resources