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.

3
  • 2
    What do you mean "if I run the Test.java to test"? How do you run it? Commented Jan 22, 2015 at 23:20
  • You example should work if you pass JavaScript variable to the SERVER. Commented Jan 22, 2015 at 23:56
  • Helpful hint, I recommend using textContent instead of innerText because the former is W3C compliant and is more universally supported. Commented Jan 23, 2015 at 7:15

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

public void doPost(HttpServletRequest request, HttpServletResponse response) 
   throws ServletException, IOException
{
    String myPostVar = request.getParameter("myPostVar");
    // ...
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.