NinjaBoy
NinjaBoy

Reputation: 3755

ajax - Why jquery replaces "+" with a space (" ")?

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.

Upvotes: 6

Views: 17894

Answers (3)

compid
compid

Reputation: 1323

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?

Upvotes: 11

bhuvin
bhuvin

Reputation: 1402

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 ??

Upvotes: 2

xdazz
xdazz

Reputation: 160923

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

Upvotes: 3

Related Questions