How to prepare encoded POST data on javascript? - javascript

I need to send data by POST method.
For example, I have the string "bla&bla&bla". I tried using encodeURI and got "bla&bla&bla" as the result. I need to replace "&" with something correct for this example.
What kind of method should I call to prepare correct POST data?
UPDATED:
I need to convert only charachters which may broke POST request. Only them.

>>> encodeURI("bla&bla&bla")
"bla&bla&bla"
>>> encodeURIComponent("bla&bla&bla")
"bla%26bla%26bla"

You can also use escape() function.The escape() function encodes a string.
This function makes a string portable, so it can be transmitted across any network to any computer that supports ASCII characters.This function encodes special characters, with the exception of: * # - _ + . /
var queryStr = "bla&bla&bla";
alert(queryStr); //bla&bla&bla
alert(escape(queryStr)); //bla%26bla%26bla
Use unescape() to decode a string.
var newQueryStr=escape(queryStr);
alert(unescape(newQueryStr)); //bla&bla&bla
Note:
escape() will not encode: #*/+
encodeURI() will not encode: ~!##$&*()=:/,;?+'
encodeURIComponent() will not encode: ~!*()'
After some search on internet, I got the following:
escape()
Don't use it.
encodeURI()
Use encodeURI when you want a working URL. Make this call:
encodeURI("http://www.google.com/a file with spaces.html")
to get:
http://www.google.com/a%20file%20with%20spaces.html
Don't call encodeURIComponent since it would destroy the URL and return
http%3A%2F%2Fwww.google.com%2Fa%20file%20with%20spaces.html
encodeURIComponent()
Use encodeURIComponent when you want to encode a URL parameter.
param1 = encodeURIComponent("http://xyz.com/?a=12&b=55")
Then you may create the URL you need:
url = "http://domain.com/?param1=" + param1 + "&param2=99";
And you will get this complete URL:
http://www.domain.com/?param1=http%3A%2F%2Fxyz.com%2F%Ffa%3D12%26b%3D55¶m2=99
Note that encodeURIComponent does not escape the ' character. A common bug is to use it to create html attributes such as href='MyUrl', which could suffer an injection bug. If you are constructing html from strings, either use " instead of ' for attribute quotes, or add an extra layer of encoding (' can be encoded as %27).
REF:When are you supposed to use escape instead of encodeURI / encodeURIComponent?
Also, as you are using JQuery, take a look at this built-in function.

Use encodeURIComponent() as encodeURI() will not encode: ~!##$&*()=:/,;?+'
This has been explained quite well at the following link:
http://xkr.us/articles/javascript/encode-compare/

More recent DOM APIs for URLSearchParams (and via URL, possibly others too) handle encoding in some cases. For example, create or use an existing URL object (like from an anchor tag) I map entries of an object as key value pairs for URL encoded params (to use for GET/POST/etc in application/x-www-form-urlencoded mimetype). Note how the emoji, ampersand and double quotes are encoded without any special handling (copied from the Chrome devtools console):
var url = new URL(location.pathname, location.origin);
Object.entries({a:1,b:"🍻",c:'"stuff&things"'}).forEach(url.searchParams.set, url.searchParams);
url.search;
"?a=1&b=%F0%9F%8D%BB&c=%22stuff%26things%22"
fetch(url.pathname, {
method: 'POST',
headers: new Headers({
"Content-type": "application/x-www-form-urlencoded"
}),
// same format as GET url search params a&b&c
body: url.searchParams
}).then((res)=>{ console.log(res); return res }).catch((res)=>{ console.warn(res); return res; });

I want POST the javascript-created hidden form.
So the question is if encodeURIComponent() should be used on each POST variable.
I haven't found the answer for Dmitry's (and my) question in this thread.
But I have found the answer in this thread.
In case of form/POST where you have upload field(s) you must use <form enctype="multipart/form-data">, if no upload field is used, you should choose yourself as described here.
Submitting the form should do the job completly, so there is no need to use encodeURIComponent() explicitly.
If you create a Http POST without using a form or without some library which creates a Http POST from your data, then you need choose an enctype= and join data yourselves.
This will be easy for application/x-www-form-urlencoded, where you will use encodeURIComponent() on each value and join them exactly as for GET request.
If you decide use multipart/form-data then ....? You should google more how to encode and join them in such case.

Related

Safari not saving cookie value correctly [duplicate]

In particular, when saving a JSON to the cookie is it safe to just save the raw value?
The reason I dopn't want to encode is because the json has small values and keys but a complex structure, so encoding, replacing all the ", : and {}, greatly increases the string length
if your values contain "JSON characters" (e.g. comma, quotes, [] etc) then you should probably use encodeURIComponent so these get escaped and don't break your code when reading the values back.
You can convert your JSON object to a string using the JSON.stringify() method then save it in a cookie.
Note that cookies have a 4000 character limit.
If your Json string is valid there should be no need to encode it.
e.g.
JSON.stringify({a:'foo"bar"',bar:69});
=> '{"a":"foo\"bar\"","bar":69}' valid json stings are escaped.
This is documented very well on MDN
To avoid unexpected requests to the server, you should call encodeURIComponent on any user-entered parameters that will be passed as part of a URI. For example, a user could type "Thyme &time=again" for a variable comment. Not using encodeURIComponent on this variable will give comment=Thyme%20&time=again. Note that the ampersand and the equal sign mark a new key and value pair. So instead of having a POST comment key equal to "Thyme &time=again", you have two POST keys, one equal to "Thyme " and another (time) equal to again.
If you can't be certain that your JSON will not include reserved characters such as ; then you will want to perform escaping on any strings being stored as a cookie. RFC 6265 covers special characters that are not allowed in the cookie-name or cookie-value.
If you are encoding static content you control, then this escaping may be unnecessary. If you are encoding dynamic content such as encoding user generated content, you probably need escaping.
MDN recommends using encodeURIComponent to escape any disallowed characters.
You can pull in a library such as cookie to handle this for you, but if your server is written in another language you will need to ensure it uses a library or language utilities to encodeURIComponent when setting cookies and to decodeURIComponent when reading cookies.
JSON.stringify is not sufficient as illustrated by this trivial example:
const bio = JSON.stringify({ "description": "foo; bar; baz" });
document.cookie = `bio=${stringified}`;
// Notice that the content after the first `;` is dropped.
// Attempting to JSON.parse this later will fail.
console.log(document.cookie) // bio={\"description\":\"foo;
Cookie: name=value; name2=value2
Spaces are part of the cookie separation in the HTTP Cookie header. Raw spaces in cookie values could thus confuse the server.

How to run encodeURIComponent with one exception?

I have a simple statement in javascript.
encodeURIComponent( "/nodes/client&123" );
I want it to exclude the slash sign / from encoding. Is there a better way to do it than this
encodeURIComponent( data.message.dav_uri ).replace("%2F","/");
The encodeURI() function will do what you want. The encodeURIComponent() function is for what its name implies: pieces of a URI, like parameter names and values.
It's safer to use encodeURIComponent() on the query string portion of a URI that your code constructs, using it separately for each parameter name and parameter value.

jQuery can't encode a parameter which is a URL

I have a GET request that takes a parameter, this parameter is also a URL. So normally I just encode the URL and then decode it in my server, this works pefectly from Java, but now I am on jQuery and I have a problem with it.
This is the value of that parameter:
http://www.BookOntology.com/bo#ania
When I encode it like this:
encodeURI(userURI)
I get the same value, while i thought that i should have gotten this
http%3A%2F%2Fwww.BookOntology.com%2Fbo%23ania
To show you what is the wrong
My current approach (which is using econdeURI) brings this final URL (note that I just want to encode the paramter not the whole URL).
http://bla bla bla?userURI=http://www.BookOntology.com/bo#ania
But in the server when i read the value of the userURI parameter i get:
http://www.BookOntology.com/bo
It is definitely a problem with the way i encode that value of that parameter because, again, the value after and before encoding is the same though the value contains some characters that should be changed.
Could you help me pass that please?
Try with encodeURIComponent function , which encodes a Uniform Resource Identifier (URI)
DEMO: encode input value
Read the MDN DOCS for more info.
encodeURI only changes characters that can't appear in a URL at all.
You're looking for encodeURIComponent which encodes all characters with special meaning in a URL as well (and makes it suitable for inserting in a query string).

encodeURI doesn't escape `equals` - why?

I have an URI like that:
http://client.dev/dap/module/hdfs-web/api/v1.0/clusters/Cluster%201%20-%20CDH4?operation=copy&to=/user/hdfs/year=2016/partial.txt&overwrite=true
I use encodeURI function to escape string. I'm wondering why spaces are encoded with %20 while equals characters are not?
encodeURI encodes a full URI, and URIs can contain = characters. For instance, if a user types in a URI, a first step to resolve it would be to call encodeURI on it.
If on the other hand you are the one constructing the URI, and the input just determines one field (for instance a search query, when given E=mc² you want to resolve https://www.google.com/search?q=E%3Dmc%C2%B2), then you are not encoding a full URI, but a URI component. Use encodeURIComponent for that:
> encodeURIComponent('= ')
'%3D%20'
The encodeURI() function is used to encode a URI.
This function encodes special characters, except:, / ? : # & = + $ # (Use encodeURIComponent() to encode these characters).
Tip: Use the decodeURI() function to decode an encoded URI.
SOURCE: W3Schools

Single quotes in string with jQuery ajax

I have run into a problem where the user enters data and if there are single quotes at all, the script errors out.
What's the best way to handle single quotes that users enter so it doesn't interfere with the jquery/javascript?
UPDATE:
I'm sending it through ajax to a database. here is the data parameter for a json ajax call.
data: "{str_" + sectionName + " :'" + UpdateText + "',EntityID: '" + EntityID + "' }",
with update text being the string that can contain the quotes.
You need to escape the quotes with a \ or depending on how you plan to use the string you can use the javascript escape and unescape functions.
alert(escape("mike's"));
alert(unescape(escape("mike's")));
Also check this out for ways to escape strings with jQuery
For escaping values in AJAX request, Do not write your own implementation of escape or use escape() method. (escape() is deprecated). Instead create a JSON object and use JSON.stringify method.
For your case it should be like (ignoring dynamic property for now):
//Create Javascript object
var obj = { SectionName: UpdateText, EntityID: EntityID };
Later in your ajax request you can do :
data: JSON.stringify(obj),
If you want to use dynamic properties with your JSON object then for your particular case you can create the object in two steps like:
var obj = { EntityID: EntityID };
obj["str_" + sectionName] = UpdateText;
This practice will save you from manually escaping single/double quotes and other invalid characters. JSON.stringify will take care of that.
(I came here looking for a somewhat similar issue, but couldn't find a suitable working solution, so ended up posting one here)
You could find one of the many String.replaceAll implementations or write your own, and just replace any single or double quotes with an escaped version like \" or \'.
Since you mentioned AJAX, there is a possibility that the strings involving single quotes are getting rejected at the server side.
Make sure you use escape string function provided , for example by php, before inserting strings, to the database.
$user_name = $_REQUEST['username'];
$user_name = mysqli_real_escape_string($conn,$user_name);
$query = "INSERT into chat(username,message) VALUES('".$user_name."')";
This helps in escaping any single or double quotes that may appear in the '$user_name' string.
Also it prevents against any kind of SQL injection atacks!
You should really sanitize your input inside your server-side script for a variety of reasons. If you're just displaying everything the user enters then your application can likely be used to launch a cross-site scripting attack.
Javascript has a built in method just for this that covers more than just single quotes. Its called encodeURIComponent, from Javascript Kit:
Used to encode the parameter portion of a URI for characters that have special meaning, to separate them from reserved characters such as "&" that act as key/value separators. More inclusive than encodeURI(), it encodes all characters with special meaning in a URL string, including "=" and "&". Use this method only on the parameter portion of a URI; otherwise, the URI may no longer be valid if it contains one of the characters that are part of a valid URI (ie: "+") yet should be escaped if part of the URI parameter.
So your code should become:
data: "{str_" + encodeURIComponent(sectionName) + " :'" + encodeURIComponent(UpdateText) + "',EntityID: '" + encodeURIComponent(EntityID) + "' }",
I encode everything I send in a query string to be safe, but encoding the EntityID could arguably be skipped because it doesn't come from the user(I'm assuming), so you know it won't have special characters.
To escape a single quote in Javascript use
UpdateText.replace('\'', '\\\'')
To escape all single quotes use
UpdateText.replace(/'/g, '\\\'')
Thanks to mbrevoort,
I elaborate more on his answer
When You are sending a single quote in a query
empid = " T'via"
empid = escape(empid)
When You get the value including a single quote
var xxx = request.QueryString("empid")
xxx = unscape(xxx)
If you want to search/ insert the value which includes a single quote in a query
xxx = Replace(empid, "'", "''")
The accepted answer should not be the solution to use.
In order to send this through AJAX to DB where request data has single quote ' in the string, do below:
Organize your request data as an object.
var data = {
"sectionName" : sectionName,
"UpdateText" : updateText,
"EntityID" : entityID
}
Stringfy your data to JSON and send with AJAX
data = JSON.stringify(data);
$.ajax({
url: "",
type: "POST",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (res) {
alert(res);
});
Depends on the Database, for SQL Server, replace your single quote ' to double quote '' to escape the single quote .
string data = date.Replace("'", "''")

Categories

Resources