I'm making an AJAX call with $.post(url, cb)
. The URL I'm passing in could potentially have weird characters like spaces, &
, ?
and so on.
Do I have to use $.post(encodeURIComponent(url), cb)
?
url
is something like /foo/weird-char§
.
Browsers automatically encode the URL i.e. it converts some special characters to other reserved characters and then makes the request. For eg: Space character ” ” is either converted to + or %20.
jQuery post() Method post() method loads data from the server using a HTTP POST request.
encodeURI is used to encode a full URL. Whereas encodeURIComponent is used for encoding a URI component such as a query string. There are 11 characters which are not encoded by encodeURI , but encoded by encodeURIComponent .
In most cases form-urlencoded data is the one to stick with because it is more or less automatic at both the client and the server end of the request. If you are deriving data from a form then it will be automatically encoded for you. If you get the data from some other source then it has to be encoded.
Do I have to use $.post(encodeURIComponent(url), cb)?
You will have to use encodeURIComponent()
but not on the entire URI, only on the data part (weird
and chars
in your example). The URL and the ? &
separating the parameters must stay intact. If you encode the entire URI, it will become unusable.
If you would add the data as POST data using the data
parameter:
url = "/foo/possible";
$.post(url, { "weird": "f2(90§§$", "chars": "ß1028490" });
jQuery's Ajax functions would take care of URL encoding the data automatically.
Yes, you would need to encode the keys and values in the query string (but not the ?
which separates the path from the query arguments and the &
which separates the query arguments). This is built into jQuery if you use the data parameter of the $.post
, like so:
$.post(url, { name: "John", time: "2pm" }, cb);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With