How can I send the "&" (ampersand) character via AJAX? - javascript

I want to send a few variables and a string with the POST method from JavaScript.
I get the string from the database, and then send it to a PHP page. I am using an XMLHttpRequest object.
The problem is that the string contains the character & a few times, and the $_POST array in PHP sees it like multiple keys.
I tried replacing the & with \& with the replace() function, but it doesn't seem to do anything.
Can anyone help?
The javascript code and the string looks like this:
var wysiwyg = dijit.byId("wysiwyg").get("value");
var wysiwyg_clean = wysiwyg.replace('&','\&');
var poststr = "act=save";
poststr+="&titlu="+frm.value.titlu;
poststr+="&sectiune="+frm.value.sectiune;
poststr+="&wysiwyg="+wysiwyg_clean;
poststr+="&id_text="+frm.value.id_text;
xmlhttp.open("POST","lista_ajax.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(poststr);
The String is:
<span class="style2">"Busola"</span>

You can use encodeURIComponent().
It will escape all the characters that cannot occur verbatim in URLs:
var wysiwyg_clean = encodeURIComponent(wysiwyg);
In this example, the ampersand character & will be replaced by the escape sequence %26, which is valid in URLs.

You might want to use encodeURIComponent().
encodeURIComponent(""Busola""); // => %26quot%3BBusola%26quot%3B

You need to url-escape the ampersand. Use:
var wysiwyg_clean = wysiwyg.replace('&', '%26');
As Wolfram points out, this is nicely handled (along with all the other special characters) by encodeURIComponent.

Ramil Amr's answer works only for the & character. If you have some other special characters, you should use PHP's htmlspecialchars() and JS's encodeURIComponent().
You can write:
var wysiwyg_clean = encodeURIComponent(wysiwyg);
And on the server side:
htmlspecialchars($_POST['wysiwyg']);
This will make sure that AJAX will pass the data as expected, and that PHP (in case your'e insreting the data to a database) will make sure the data works as expected.

You can pass your arguments using this encodeURIComponent function so you don't have to worry about passing any special characters.
data: "param1=getAccNos&param2="+encodeURIComponent('Dolce & Gabbana')
OR
var someValue = 'Dolce & Gabbana';
data: "param1=getAccNos&param2="+encodeURIComponent(someValue)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

You could encode your string using Base64 encoding on the JavaScript side and then decoding it on the server side with PHP (?).
JavaScript (Docu)
var wysiwyg_clean = window.btoa( wysiwyg );
PHP (Docu):
var wysiwyg = base64_decode( $_POST['wysiwyg'] );

The preferred way is to use a JavaScript library such as jQuery and set your data option as an object, then let jQuery do the encoding, like this:
$.ajax({
type: "POST",
url: "/link.json",
data: { value: poststr },
error: function(){ alert('some error occured'); }
});
If you can't use jQuery (which is pretty much the standard these days), use encodeURIComponent.

encodeURIComponent(Your text here);
This will truncate special characters.

Related

What is the JavaScript equivalent of php's FILTER_SANITIZE_STRING?

I would like to filter text input from a form using JavaScript. Php's FILTER_SANITIZE_STRING Strips tags, and optionally strips or encode special characters. But I can't use php for what I am doing I need a JavaScript equivalent
You can write such function yourself. It's not that difficult. The default settings are shown below. If you want to support flags like PHP's filters do, then you need to add more to this function.
function FILTER_SANITIZE_STRING (string) {
string = string.replaceAll(/\x00|<[^>]*>?/g, '');
string = string.replaceAll('\'', ''');
string = string.replaceAll('"', '"');
return string;
}
// testing
console.log(FILTER_SANITIZE_STRING('<abc>\'"qwe'));
The question is why would you want to do that? PHP is removing this particular filter because of its lack of usefulness. This filter has no practical application. You'd be better off writing a function for an actual requirement rather than trying to replicate this useless filter.

How to remove unwanted encoding symbols in json

I have json on my page coming from the string property of the model:
var myJson = '[{\"A\":1,\"B\":10,\"C\":\"214.53599548339844\",\"D\":\"72.52798461914062\"},
{\"A\":1,\"B\":11,\"C\":\"214.53599548339844\",\"D\":\"72.52798461914062\"}]'
I want to process that json via javascript on the page
I am doing $.parseJSON(#Html.Raw(Json.Encode(myJason))); but json still contain \" symbol. If i do $.parseJSON(#Html.Raw(Json.Decode(myJason))); it is just producing an $.parseJSON(System.Web.Helpers.DynamicJsonArray); How can I fix that?
Take your JSON and .stringify() it. Then use the .replace() method and replace all occurrences of ("\").
var myString = JSON.stringify(myJson);
var myNewString = myString.replace(/\\/g, "");
Hope this helps.
There are two ways
1 from where you get the JSON asked them to send you as url encoded format. at your end you need to decode url and you will get the Perfect JSON.
Other wise do the laborious replace method for each and every special charecter with respective char.
like above example you need to use replace("\","");
There is no JSON parser that will be able to deal with a JSON string that isn't properly formatted in the first place.
so you need to make sure that your theModel is formatted appropriately and according JSON.org standards.
Like
Koushik say you can use String operation

encoding json to string

I'm interested how does google encode POST params.
In one of a application I've found the following approach, let say I have the following object:
selection={"ty":"mc","cl":{"loc_type":0,"si":9,"aps":false},"sr":[]}
In POST request it takes the following form:
selection=%7B%22ty%22%3A%22mc%22%2C%22cl%22%3A%7B%22loc_type%22%3A0%2C%22si%22%3A9%2C%22aps%22%3Afalse%7D%2C%22sr%22%3A%5B%5D%7D
Which is method is applied here?
The same effect can be achieved by using encodeURIComponent and JSON.stringify functions:
"selection=" + encodeURIComponent(JSON.stringify(selection))
It's simply URL encoding
Check out the built-in function encodeURIComponent(str) and encodeURI(str)
the method in javascript is called encodeURIComponent() write
alert(encodeURIComponent('{"ty":"mc","cl":{"loc_type":0,"si":9,"aps":false},"sr":[]}'));
It is called URL-Encoding.
It replaces non-ASCII characters and characters that have a special meaning in the URI scheme with a ASCII representation: Each character that isn't printable will be written as %xy where xy is the index inside the ASCII table of that character.
There are many programming languages supporting it out-of-the-box:
In JavaScript you can use the encodeURIComponent() or encodeURI() function.
You can easily invoke it like this, e.g.:
var myjson = '{my:json}';
url_encoded_json = encodeURIComponent( myjson );
alert(url_encoded_json);
In other languages:
PHP has the rawurlencode() function.
ASP has the Server.URLEncode() function.
Python has the urllib.urlencode() function.
Java has the java.net.URI(url).toASCIIString() function

Can you create a JavaScript string without using ' or " quotes?

I have a JS file with some XML in it, where the XML is supposed to get converted to a word by the server.
E.g.
var ip = "<lang:cond><lang:when test="$(VAR{'ip_addr'})">$(VAR{'ip_addr'})</lang:when></lang:cond>";
This gets converted to:
var ip = "192.168.0.0";
However, in case the server doesn't work as intended, I don't want there to be a syntax error, and this is VERY important. Currently there would be a syntax error because the language uses both types of quotes. I can't think of a way to get around this, but perhaps there's another way to do quotes in JavaScript? Or to create a string?
For example, in Python I'd use triple quotes:
ip = """<lang:cond><lang:when test="$(VAR{'ip_addr'})">$(VAR{'ip_addr'})</lang:when></lang:cond>"""
Anyone have a bright idea?
I have had to create strings without quotes for a project as well. We were delivering executable client javascript to the browser for an internal website. The receiving end strips double and single quotes when displayed. One way I have found to get around quotes is by declaring my string as a regular expression.
var x = String(/This contains no quotes/);
x = x.substring(1, x.length-1);
x;
Using String prototype:
String(/This contains no quotes/).substring(1).slice(0,-1)
Using String.fromCharCode
String.fromCharCode(72,69,76,76,79)
Generate Char Codes for this:
var s = "This contains no quotes";
var result = [];
for (i=0; i<s.length; i++)
{
result.push(s.charCodeAt(i));
}
result
In JavaScript, you can escape either type of quote with a \.
For example:
var str = "This is a string with \"embedded\" quotes.";
var str2 = 'This is a string with \'embedded\' quotes.';
In particular, your block of JavaScript code should be converted to:
var ip = "<lang:cond><lang:when test=\"$(VAR{'ip_addr'})\">$(VAR{'ip_addr'})</lang:when></lang:cond>";
In general, I always prefer to escape the quotes instead of having to constantly switch quote types, depending upon what type of quotes may be used within.
I was looking for a solution to the same problem. Someone suggested looking at https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/template_strings which proved helpful. After reading about half the article, it stated that you can create strings with the backward tick character. (`)
Try this :)
document.getElementById('test').innerHTML = `'|'|'|"|"`
<div id="test" style="font-size:3em;"></div>
You can't create a string without using a single or double quote, as even calling the String() prototype object directly still requires you to pass it the string.
Inside XML you would use CDATA, but inside JS you'll have to just escape the '\"strings\"' "\'appropriately\'"

Best way to store JSON in an HTML attribute?

I need to put a JSON object into an attribute on an HTML element.
The HTML does not have to validate.
Answered by Quentin: Store the JSON in a data-* attribute, which is valid HTML5.
The JSON object could be any size - i.e. huge
Answered by Maiku Mori: The limit for an HTML attribute is potentially 65536 characters.
What if the JSON contains special characters? e.g. {foo: '<"bar/>'}
Answered by Quentin: Encode the JSON string before putting it into the attribute, as per the usual conventions. For PHP, use the htmlentities() function.
EDIT - Example solution using PHP and jQuery
Writing the JSON into the HTML attribute:
<?php
$data = array(
'1' => 'test',
'foo' => '<"bar/>'
);
$json = json_encode($data);
?>
CLICK ME
Retrieving the JSON using jQuery:
$('a').click(function() {
// Read the contents of the attribute (returns a string)
var data = $(this).data('json');
// Parse the string back into a proper JSON object
var json = $.parseJSON($(this).data('json'));
// Object now available
console.log(json.foo);
});
The HTML does not have to validate.
Why not? Validation is really easy QA that catches lots of mistakes. Use an HTML 5 data-* attribute.
The JSON object could be any size (i.e. huge).
I've not seen any documentation on browser limits to attribute sizes.
If you do run into them, then store the data in a <script>. Define an object and map element ids to property names in that object.
What if the JSON contains special characters? (e.g. {test: '<"myString/>'})
Just follow the normal rules for including untrusted data in attribute values. Use & and " (if you’re wrapping the attribute value in double quotes) or ' (if you’re wrapping the attribute value in single quotes).
Note, however, that that is not JSON (which requires that property names be strings and strings be delimited only with double quotes).
Depending on where you put it,
In a <div> as you asked, you need to ensure that the JSON does not contain HTML specials that could start a tag, HTML comment, embedded doctype, etc. You need to escape at least <, and & in such a way that the original character does not appear in the escaped sequence.
In <script> elements you need to ensure that the JSON does not contain an end tag </script> or escaping text boundary: <!-- or -->.
In event handlers you need to ensure that the JSON preserves its meaning even if it has things that look like HTML entities and does not break attribute boundaries (" or ').
For the first two cases (and for old JSON parsers) you should encode U+2028 and U+2029 since those are newline characters in JavaScript even though they are allowed in strings unencoded in JSON.
For correctness, you need to escape \ and JSON quote characters and it's never a bad idea to always encode NUL.
If the HTML might be served without a content encoding, you should encode + to prevent UTF-7 attacks.
In any case, the following escaping table will work:
NUL -> \u0000
CR -> \n or \u000a
LF -> \r or \u000d
" -> \u0022
& -> \u0026
' -> \u0027
+ -> \u002b
/ -> \/ or \u002f
< -> \u003c
> -> \u003e
\ -> \\ or \u005c
U+2028 -> \u2028
U+2029 -> \u2029
So the JSON string value for the text Hello, <World>! with a newline at the end would be "Hello, \u003cWorld\u003e!\r\n".
Another way you can do it – is put json data inside <script> tag, but not with type="text/javascript", but with type="text/bootstrap" or type="text/json" type, to avoid javascript execution.
Then, in some place of your program, you can ask for it in this way:
function getData(key) {
try {
return JSON.parse($('script[type="text/json"]#' + key).text());
} catch (err) { // if we have not valid json or dont have it
return null;
}
}
On server side, you can do something like this (this example with php and twig):
<script id="my_model" type="text/json">
{{ my_model|json_encode()|raw }}
</script>
Another option is to base64 encode the JSON string and if you need to use it in your javascript decode it with the atob() function.
var data = JSON.parse(atob(base64EncodedJSON));
For simple JSON objects, the code below would work.
Encode:
var jsonObject = { numCells: 5, cellWidth: 1242 };
var attributeString = escape(JSON.stringify(jsonObject));
Decode:
var jsonString = unescape(attributeString);
var jsonObject = JSON.parse(jsonString);
You can use knockoutjs,
<p>First name: <strong data-bind="text: firstName" >todo</strong></p>
<p>Last name: <strong data-bind="text: lastName">todo</strong></p>
knockout.js
// This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI
function AppViewModel() {
this.firstName = "Jayson";
this.lastName = "Monterroso";
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());
Output
First name: Jayson
Last name: Monterroso
Check this:
http://learn.knockoutjs.com/
Nothing fancy here. From PHP, give the JSON string a run through htmlspecialchars to make sure no special characters can be interpreted as HTML. From Javascript, no escaping necessary; just set the attribute and you're good to go.
Another thought that could be used is store the JSON data as a base64 string in the attribute and then using window.atob or window.btoa to restore it to usable JSON data.
<?php
$json = array("data"=>"Some json data thing");
echo "<div data-json=\"".base64_encode(json_encode($json))."\"></div>";
?>
What you can do is use cdata around your element/s like this
<![CDATA[ <div class='log' mydata='${aL.logData}'>${aL.logMessage}</div> ]]>
where mydata is a raw json string. Hope this helps you and others.
In our case replace ' by ' and inserting the json between simple quotes works perfectly for vue:
php:
$data = json_encode($data);
$data = preg_replace("/'/", ''', $data);
html:
<vue_tag :data='<?=$json?>' />

Categories