I'm working on this problem for hours but I can't find a solution. I think it's just a syntax error.
In my simple project I just want to send a JSON string to the Servlet with a name and a text in it. The servlet should take it, parse it with the org.json lib and print the name and text out. After that send it back to that Java Script, also as a JSON String.
I have tried multiple syntax versions I found on the internet but nothing works correct.
Here are the main parts of the project:
JS:
function sendMessage(event){
request = new XMLHttpRequest();
request.onreadystatechange = receivedData
var chat_text = document.getElementById("textarea_input").value;
request.open("GET", "AjaxChatServlet", true)
var jsonData;
jsonData = JSON.stringify({ username : loginname, text : chat_text});
request.setRequestHeader("Content-type", "application/json");
request.setRequestHeader("Content-length", jsonData.length);
request.send(jsonData)
document.getElementById("textarea_input").value = "";
}
Servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
JSONObject jobj_username = null;
try {
jobj_username = new JSONObject(request.getParameter("username"));
} catch (JSONException e) {
// TODO Automatisch generierter Erfassungsblock
e.printStackTrace();
}
JSONObject jobj_text = null;
try {
jobj_username = new JSONObject(request.getParameter("text"));
} catch (JSONException e) {
// TODO Automatisch generierter Erfassungsblock
e.printStackTrace();
}
System.out.println("\n\n\nMessage send from:\n" + jobj_username + "\n\n" + "Message content:\n" + jobj_text);
PrintWriter writer = response.getWriter();
if(jobj_username != null && jobj_text != null){
//send JSON back to JavaScript
}else{
{writer.print("no Data available");}
}
}
Hope someone could help me. Thanks