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.

4
  • 1
    Same question as this stackoverflow.com/questions/28100431/… , didnt you get the answer Commented Jan 23, 2015 at 8:53
  • Anyway you have to submit the form. Better make an AJAX POST call and on servlet get the parameter. Same as mentioned by San. Commented Jan 23, 2015 at 9:07
  • No i did not get the answer. maybe you know some other solution that could work Commented Jan 23, 2015 at 9:09
  • Use this into your javascript window.location.href = 'url?parameter=' + myval Commented Jan 28, 2015 at 10:08

1 Answer 1

0

You use doGet instead of doPost

type: 'POST'

Change it to GET or use doPost in your Java project

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

2 Comments

i tried that, but did not work
Which of the two suggestions did you exactly try? You should change the servlet to doPost(). Parameters in a GET request are passed in the url, not in the request body.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.