6

I am having a problem here. When I use ajax to pass a parameter containing "+" to my controller it is being replaced by a space.

Example, I will pass value = Tom+Jerry+Garfield using ajax. When I use System.out.println() in my controller it displays Tom Jerry Garfield. I tried using other special characters I don't seem to have a problem.

Please help. Thanks in advance.

NinjaBoy
  • 3,715
  • 18
  • 54
  • 69
  • [Spaces in the query part of URLs are always encoded as plus signs](http://tools.ietf.org/html/rfc3986#section-3.4). So your controller is simply decoding them. Sounds like you're not properly constructing your URLs, since it sounds like you want a plus sign (which needs to be encoded) an not a space. If you use %2B instead it should work, but you shouldn't be doing this manually like you're doing now. – bzlm Jul 12 '12 at 08:00
  • Not jQuery is replacing the characters, the server is... – Felix Kling Jul 12 '12 at 08:01
  • @FelixKling You mean tomcat is doing this? What is the solution for this? – NinjaBoy Jul 12 '12 at 08:01
  • possible duplicate of [AJAX POST and Plus Sign ( + ) -- How to Encode?](http://stackoverflow.com/questions/1373414/ajax-post-and-plus-sign-how-to-encode) – bzlm Jul 12 '12 at 08:04

3 Answers3

11

In some GET and POST requests (most likely in the URL, or via a form), spaces are encoded as "+" (plus) symbols before they are passed to the server. You can see this behaviour if you do a normal GET request - you will see something like google.com?q=test+example If you want to pass a plus symbol via an ajax GET/POST request, you need to "urlencode" it. The URL encoded value for + is %2B.

Also note:

The javascript encodeURIComponent() function can be used, as answered in:

AJAX POST and Plus Sign ( + ) -- How to Encode?

Community
  • 1
  • 1
compid
  • 1,313
  • 9
  • 15
  • Note that the "real" encoding for space is actually %20, the + (plus) symbol is actually an alternative (older) form http://stackoverflow.com/a/1634293/1407034 – compid Jul 12 '12 at 08:10
3

+ is decoded as space after url decoding. If you want to pass +, you need to encode it.

xdazz
  • 158,678
  • 38
  • 247
  • 274
2

When we pass values to the controller there is a model binder which is sitting in between the request. When the ajax call is made the url and the request is encoded. The " " (Space) character in url decoded form encodes to a "+".
The Model Binder on the other hand decodes the request and extracts the parameters and gives it to the controller and hence "+" is converted to a " " . But here the question is why would one pass "+" as a separator ??

bhuvin
  • 1,382
  • 1
  • 11
  • 28
  • I don't think it was intended as a separator, but as an actual plus sign ("Tom plus Jerry plus Garfield"). – bzlm Jul 12 '12 at 08:05
  • @bzlm - Might be the case ... Possibly in that case %2B is the way to go. But i still am wondering about the use case ! – bhuvin Jul 12 '12 at 08:09