0

I am trying to POST a JSON object to a servlet via AJAX. However, the object is null in the servlet. I am unable to figure out what's wrong with this code.

JAVASCRIPT

function submitValues(event, val1, val2) 
{    
var xmlHttpObj = new XMLHttpRequest();                
            if(window.XMLHttpRequest) 
            {
                xmlHttpObj = new XMLHttpRequest();                    
             }
            else if(window.ActiveXObject)
            {
                xmlHttpObj = new ActiveXObject("Microsoft.XMLHttp");

            }


     var jsonObject =  submitTheValues(event, val1, val2);
       alert("json is:" +jsonObject);
     var json = JSON.stringify(jsonObject);
       alert("json after stringify:" +json);

        xmlHttpObj.open("POST", "../myapp/myservlet", true);
        xmlHttpObj.setRequestHeader("Content-type", "application/json");                    
        xmlHttpObj.send(json);

}  

SERVLET

String jsonObj = request.getParameter("json");

1 Answer 1

1

If you want to receive the data as a parameter you'll have to send it as application/x-www-form-urlencode.

xmlHttpObj.open("POST", "../myapp/myservlet", true);
xmlHttpObj.setRequestHeader("Content-type", "application/x-www-form-urlencode");                    
xmlHttpObj.send('json='+encodeURIComponent(json));
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a ton. I had struggled with this quite a bit. It just worked fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.