Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery $.post - do I have to encode the URL parameter?

Tags:

jquery

url

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

like image 559
nornagon Avatar asked Mar 09 '11 10:03

nornagon


People also ask

Does browsers automatically encode URL?

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.

What is jQuery post?

jQuery post() Method post() method loads data from the server using a HTTP POST request.

What is the difference between encodeURI and encodeURIComponent?

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 .

Is the data part of an Ajax request automatically Urlencoded yes or no?

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.


2 Answers

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.

like image 120
Pekka Avatar answered Dec 04 '22 19:12

Pekka


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);
like image 37
Adam Ayres Avatar answered Dec 04 '22 19:12

Adam Ayres