Encoding (+) symbol in ajax request jQuery / jQuery ajax request removing (+) sign / How to send ‘+’ through AJAX post

Scenario

There may be a scenario where you are sending HTML form fields in ajax POST request or sending the value of a particular form field (let’s say input box) as a parameter in ajax request. For Example, suppose there is an input box on a web page with id “userName” and you send its value to the server in an ajax request as :

$.ajax({
url : ‘submitRequest’,
data : “uname=” + $(“#userName”).val()
});

When this request is fired, the value typed in the input box is sent with parameter “uname” to the server. Let’s say the user types in his name as “codippa”. At the server, the request parameter “uname” will have the value “codippa”. So far it is correct.

But what if, the user types “codippa+1”. The value of request parameter “uname” received on the server in this case will be “codippa 1”. Where is the plus sign? It is replaced with a space.

Reason

There are some characters which have special meaning. Some such characters are ‘+, %,=, &, # ‘ etc. ‘+’ character is interpreted as a space on the server side. When used in form fields it is replaced by spaces. When sending the ajax request, you can easily see ‘+’ replaced with a space in the browser console.

Similarly ‘&‘ character is treated as a separator between parameters. So if you type “codippa&1” in the text box then the value sent to the server will be “codippa” as the server will assume that it has received two parameters, “uname” and “1” with the value of “uname” as “codippa” and value of “1” as null.

Solution

In order to send special symbols such as +, &, = etc., to the server, they need to be encoded. Javascript provides a method encodeURIComponent()which encodes all special characters present in the string passed to it. So in the above ajax request, if the “uname” parameter is sent as

data : “uname=” + encodeURIComponent( $(“#userName”).val() )

then if the user types in “codippa+1“, the value received at the server will be the same, that is, ‘+’ will not be removed.

Note : encodeURIComponent() will not encode the symbols: ~!*()'

Hope this post helped you to solve a problem. If yes, do not forget to comment and share.

Leave a Reply