I am facing an issue while sending special characters in ajax POST request, these special characters are not received properly by my servlet where the request is sent.
Javascript code:
myAjaxPostrequest=new GetXmlHttpObject();
var parameters1="content="+mainContent;
myAjaxPostrequest.open("POST", "controller", true);
myAjaxPostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myAjaxPostrequest.send(parameters1);
Servlet code:
String lsContentToSave = aoReq.getParameter("content");
System.out.println(lsContentToSave);
aoReq is HttpServletRequest object.
For eg. if the special character is » it prints »
I have also tried jquery post and still facing the same issue. Please let me know the fix for this.
You tagged
jquery-ajax, but the JS code in your question isn’t recognizeable as jQuery. Are you really using jQuery? That look more like a ripoff of the poor w3schools tutorial.In any way, you need to take the character encoding into account in 2 places. In the client side, when you form-encode the parameter, you should be using
encodeURIComponent(). This will apply percent encoding using UTF-8.In the server side, before you get any parameter from the request body, you should set the request encoding to UTF-8 as follows:
That said, if you were really using jQuery, then you don’t need to worry about using
encodeURIComponent()in the client side. jQuery will handle it all for you if you’re using$.post()function with a data object.