jQuery can't encode a parameter which is a URL - javascript

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).

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.

Passing encoded url as parameter javascript function

JS fiddle created at https://jsfiddle.net/ankitwasankar/sc50ecyf/ demonstrates, how the url sent as a parameter decode itself inside function. Is it the expected behaviour. Do I need to encode url passed as parameter again inside function. Currently when URL is opened with window.location.href it doesn't contain %26 instead contains &. So on server, HttpServletRequest.getParameterNames() returns two parameters instead of one.
What about split %26 in-between, like:
<a href='javascript:print_me("https://www.google.co.in/search?query=a%2" + "6b=26")'>Click</a>
This prevents the auto-decoding, although it's a little bit hacky.

Passing URL as string -- everything after '&' gets lost

I have an MVC application that makes an API call in an onclick event
#Model.MyApiCall is a string that looks something like this:
window.location = 'http://localhost/myPath?myImagePath=http://myimagepath&width=360&category=2'
This successfully calls my API. So far so good.
However, for some reason everything after & is getting cut off from myImagePath. So instead of myImagePath equaling what was sent from my click, I'm only getting this:
http://myimagepath
You have to encode your query string parameter. You can do it in javascript:
window.location = 'http://localhost/myPath?myImagePath=' + encodeURIComponent('http://myimagepath') + '&width=360&category=2'
using encodeURIComponent.
You can also do it inside your MVC controller using HttpUtility.UrlEncode only on the http://myimagepath part of your Model.MyApiCall.
[Edit]
If your myImagePath parameter is the entire http://myimagepath&width=360&category=2 string then of course Steve Danner is right and you should follow his answer.
The ampersand (&) is a special character and needs to be encoded to be properly parsed by the browser. You'll need to break up your query string and actual path into separate strings. Something like this:
<a href="javascript://" onclick="#(Model.MyApiCallPath +
HttpUtility.UrlEncode(Model.MyApiCallQueryString))"></a>
Your final js will look something like:
window.location = 'http://localhost/myPath?myImagePath=http%3A%2F%2Fmyimagepath%26width%3D360%26category%3D2';
You are trying to pass a url as a url parameter. Since the url in question contains special characters, you need to escape/encode the uri components.
Since you're using ASP.Net, you should wrap the string with:
window.location = Uri.EscapeUriString('http://localhost/myPathmyImagePath=http://myimagepath&width=360&category=2')

encoding issue on form.serialize(); Some specials character displaying as ASCII code

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.

How can I submit a hash key in an URL parameter?

I have a Spring-MVC application with Freemarker as the view component.
In my templates, several links are generated which point back to my application and which include URL parameters containing a hash key (#).
Example:
parameter: Q#106368 11
URL generated by Freemarker with encoded param: testurl.html?key=Q%23106368%2011
I use JavaScript to redirect to this URL (reason: I use JS to manage loading of 2 frames at the same time).
The redirect method is simple:
function redir(url) {
window.location.href = url;
}
The JS call generated by Freemarker looks like
test
My problem is that the browser / Javascript converts back the URL encoded parameter, thinks there is a # and cuts off there.
When I use window.location.href='http://...' directly it works. Only when using the method parameter it seems to be magically URL decoded and then the redirect fails because the URL gets cut off at the #.
Is there an easy way to transmit the parameter correctly?
I am aware that I could replace the #, e.g. with $$$hash$$$, in the template and do the replacement on the server side again. But there are so many places I would have to change...
As Marc B commented, it is necessary to URL encode again. The method would be encodeURI(). However, this method does not encode the # sign. For my specific use case, I have to replace the # sign with %23 after the encoding.
The redirect JS method finally looks like:
function redir(url) {
url = encodeURI(url);
url = url.replace(/#/g, '%23');
window.location.href = url;
}
Comparing escape(), encodeURI(), and encodeURIComponent()
encodeURIComponent/decodeURIComponent is more thorough than just encodeURI, it will decode/encode '#' and event '/'
What browser are you using? I'm trying FireFox 5 and it doesn't convert %23 back into # in my testing. When you mouse over the link or copy the link location, what does that have? Are you sure whatever is outputting the link isn't doing the conversion?
Update
This isn't ideal, but it seems like it solves the problem:
<a onclick="url = 'http://localhost:8080/testappp/testurl.html?key=Q%23106368%2011';" href="javascript:redir(url);">test</a>
It seems like the href attribute is decoded. When I mouse over it I seen the # instead of the %23.

Categories

Resources