0

I want to use request.getparameter to determine the action for an event for my page. Example Add or Delete button.

But when I have the button to onsubmit="post();return false;" the Javascript for an ajax to return a content-type application/json the request.get parameter is always null.

When I remove the the onsubmit method I will get the request parameter equal "add".

In this case how should I determine the action so that I can have different button on the page.

JavaScript
function post() {
    var xhttp;
    if (window.XMLHttpRequest) {
        // code for modern browsers
        xhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xhttp.onreadystatechange = function () {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
            document.getElementById("postView").innerHTML = xhttp.responseText;
        }
    };
            //Do someting
    xhttp.open("POST", "myServlet", true);
    xhttp.setRequestHeader("Content-Type", "application/json");
    xhttp.send(jsonObj);
}

HTML Form
<form name="myForm" action="myServlet" method="post" onsubmit="post();return false;">
Name: <input type="text" id="fnText">
<input type="submit" name="add" value="Add" />
</form>


Java Servlet
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("Method "+request.getMethod());           
String add = request.getParameter("add");
System.out.println("getParameter is " + add);
}
newbieprogrammer
  • 848
  • 7
  • 23
  • 46

2 Answers2

0

you are not setting the value of jsonObj, you need to pass it, otherwise you will receive no values.

here is an example of what you should send:

xmlhttp.open("POST", "/myServlet");
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({"add":"add"}));
0

When you send the request through the ajax call (i.e. using the post() function), you are not passing the values for the form.

When you remove the onsubmit method, you are using the action of the form and the form is getting encoded and sent in the http request.

Note: You should consider using jQuery, then your javascript code will be much simplified.

See this post: Pass entire form as data in jQuery Ajax function

Community
  • 1
  • 1
Michael Markidis
  • 4,163
  • 1
  • 14
  • 21