user4058411
user4058411

Reputation:

How to send parameters from ajax to servlet

I am trying to add 2 numbers using servlets and ajax/javascript. I am getting java.lang.NumberFormatException: and the values are null. Can i know how to pass parameters from ajax to servlet.

SumWithAjaxServlet.java

public class SumWithAjaxServlet extends HttpServlet  {
     protected void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException
        {
            PrintWriter out = response.getWriter();

            System.out.println("n1 : "+request.getParameter("n1"));
            System.out.println("n2 : "+request.getParameter("n2"));

            int num1 = Integer.parseInt(request.getParameter("n1"));
            int num2 = Integer.parseInt(request.getParameter("n2"));
            out.println(num1+num2+"");
        }
}

index.jsp

<script type="text/javascript">
  function calc() 
{ 
    var xmlHttp = new XMLHttpRequest(); 
    var value1 = document.getElementById("n1").value; 
    var value2 = document.getElementById("n2").value; 

    xmlHttp.open("POST", "SumWithAjaxServlet", true); 
    xmlHttp.send(value1 + "," + value2); 

    var result = document.getElementById("result"); 
    result.innerHTML = xmlHttp.responseText; 
}
</script> 
<body>
<form id='calcForm'>
        <table border="3">
            <tr>
                <td>Enter 1st number :</td>
                <td><input type="text" name="n1" id="n1"></td>
            </tr>
            <tr>
                <td>Enter 2nd number :</td>
                <td><input type="text" name="n2" id="n2"></td>
            </tr>
            <tr>
                <td>Result :</td>
                <td><input type="text" value="" id="result"></td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td><input type="button" id="calculate" value="calculate"
                    onclick="calc()" /></td>
            </tr>
        </table>
    </form>
</body>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app>

    <servlet>
        <servlet-name>SumWithAjaxServlet</servlet-name>
        <servlet-class>SumWithAjaxServlet</servlet-class>
    </servlet>

    <servlet-mapping>
            <servlet-name>SumWithAjaxServlet</servlet-name>
            <url-pattern>/SumWithAjaxServlet</url-pattern>
    </servlet-mapping>

   <welcome-file-list>  
        <welcome-file>index.jsp</welcome-file>  
   </welcome-file-list> 

</web-app>

Upvotes: 1

Views: 13116

Answers (2)

Sas
Sas

Reputation: 2503

You can try using jquery to do the same with $.post. Something like this:

var value1 = $("#n1").val(); 
var value2 = $("#n2").val();
$.post( "SumWithAjaxServlet", { n1: value1, n2: value2})
.done(function( data ) {
 result.innerHTML = data;
});

http://api.jquery.com/jquery.post/

Update:

As @Quentin mentioned you need to change:

xmlHttp.send(value1 + "," + value2); 

to

xmlhttp.send("n1=value1&n2=value2");

In addition you can try converting your values to integer before you passed it in like this:

 var value1 = parseInt(document.getElementById("n1").value); 
 var value2 = parseInt(document.getElementById("n2").value); 

Other than that everything look fine to me.

  var asyncRequest;
  function getSum()
  {
     var value1 = parseInt(document.getElementById("n1").value); 
     var value2 = parseInt(document.getElementById("n2").value);
     var url ="SumWithAjaxServlet";
     try
     {
        asyncRequest = new XMLHttpRequest();
        asyncRequest.addEventListener("readystatechange", stateChange, false); 
        asyncRequest.open( "POST", url, true );
        asyncRequest.send("n1=" + value1 + "&n2=" + value2); 
     }
     catch ( exception )
     {
        alert( "Request failed." );
     }
  } 

  function stateChange()
  {
     if ( asyncRequest.readyState == 4 && asyncRequest.status == 200 )
     {
        document.getElementById("result").innerHTML =asyncRequest.responseText;
     } 
  } 

Upvotes: 1

Quentin
Quentin

Reputation: 943562

You are sending your data using a non-standard, custom encoding, but trying to parse it as if it were encoded using the standard form url encoding.

Given, for the sake of example, that your values are 333 and 555: You are sending the string 333,555. You need to send the string n1=333&n2=555.

Upvotes: 2

Related Questions