17

I'm using jQuery's $.ajax method to send and retrieve data to a REST service. Some of the URL's I'm providing to the $.ajax method requires spaces and other special characters to be encoded.

The problem lies with Chrome, Safari (Webkit) and Internet Explorer browsers. Firefox POST's to a URL which is encoded but the other browsers POST to a URL which isn't encoded.

As an example:

$.ajax ({
  url: "http://localhost:8080/rest/123/Product Line A/[Product Type B]",
  type: "POST",
  dataType: "json",
  data: { ... },
  success: function(...){},
  error: function(...){}
})

Firefox POSTS the URL in the following format:

http://localhost:8080/rest/123/Product%20Line%20A/%5BProduct%20Type%20B%5D

Chrome, Safari and IE POSTS the URL in the following format:

http://localhost:8080/rest/123/Product Line A/[Product Type B]

The REST services accepts the encoded (Firefox) format - is there a way I can make this consistent across all browsers?

Thanks in advance!

4 Answers 4

23

You can use javascript's encodeURI() function to encode a URL into "Firefox format" as you state.

Sign up to request clarification or add additional context in comments.

Comments

7

Passing [Product Type B] in unencoded form is invalid, so what the browsers make of it is undefined.

Do a encodeURIComponent() on the product type part.

3 Comments

Is "Product Line B" also invalid? I'll give this a go the only problem it occurs and deeper and deeper levels just have to be careful I guess.
@schone yup, it is too. encodeURI() is more convenient because it allows you to run through the entire URL at once
encodeURIComponent() encodes / into %2F, which gives me the error Uncaught SyntaxError: Unexpected token C when used in the $.ajax url.
3

I think .serialize() would be the jquery way to do this.

check here: http://api.jquery.com/serialize/

also there is a plugin for jquery: http://plugins.jquery.com/project/URLEncode

or the javascript way ... encodeURIComponent()

check here: http://www.w3schools.com/jsref/jsref_encodeURI.asp

3 Comments

When I tried encodeURIComponent() it seemed to encode the slashes as well which breaks the URL.
@schone pass each component to encodeURIComponent() separately, then join them together with the slashes. This is intentional and correct so that you can have a slash in the component and it will be encoded accordingly.
@ShivanRaptor there is Trusting and trusting, w3schools is good for the basics, sometimes much better than some unqualified comment on an answer on stackoverflow, see above.
1

The quick fix would be to encodeURI() the URL before passing to $.ajax. You could also replace the $.ajax function with a thin wrapper to take the {} literal and encodeURI the URL before passing to the original function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.