Search code examples
javascriptajaxpostcontent-typeurl-encoding

How to escape + in post call content type as application/x-www-form-urlencoded


I have a ajax call with content type: xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

Now I have a data like: "firstName=bob+builder";

When the data is sent to the server the browser replaces the + sign with space and the data goes as firstName: bob builder

Is there a way to escape that + sign? as far as I know there is no way except that it should be handled on the server side, replacing space with + sign. Am I wrong?


Solution

  • You should be able to encode on the client side. With Javascript:

    encodeURIComponent("bob+builder"); //bob%2Bbuilder
    

    The server side code should then simply decode.