0

I want to pass a javascript variable to a java servlet. I am developing a web application. This is my html code:

<p id="test">Some text</p>

And this is what i write in the javascript file:

var myVar = document.getElementById('test').innerText;

$.ajax({
    url: 'Test',
    data: {
        myPostVar: myVar
    },
    type: 'POST'
});

And then this in the servlet (in the doGet):

String result = request.getParameter("myPostVar");
System.out.print(result);

And if i run the Test.java to test, it gives me "null". I googled too much but could not find any solution.

user2959870
  • 80
  • 6
  • 25

2 Answers2

2

The problem is you have the post method in your ajax and you are trying to get it in the doGet() of your servlet.

Use doPost or change the method to Get in your ajax.

Santhosh
  • 8,181
  • 4
  • 29
  • 56
0

Try this:

public void doPost(HttpServletRequest request, HttpServletResponse response) 
   throws ServletException, IOException
{
    String myPostVar = request.getParameter("myPostVar");
    // ...
}
Stephan
  • 41,764
  • 65
  • 238
  • 329