Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending a value from JavaScript to JSP (with jQuery)

Right now I have a JSP page that allows to sort some items, when is ready and a link is clicked a JavaScript function converts all the info into XML (text in a variable), after this i need to send this XML to the JSP page again, i tried putting the info in a hidden input and submitting the form, sending with $.post and a few more jQuery functions but nothing worked. Any ideas?

In my JSP I'm reading the post like this:

<% out.println(request.getParameter("data")); %>

This doesn't work:

xml = "<xml></xml>";
$("#form").submit(function(){
   alert("JS: " + $("#data").text());
   $("#data").text(xml);
});

This either:

xml = "<xml></xml>";
$("#data").text(xml);
$("#form").submit();

And replacing .text with .html doesn't work too. Any ideas are welcome, thx

like image 383
Juan Techera Avatar asked Dec 30 '08 19:12

Juan Techera


1 Answers

You're probably going the wrong way here. You didn't provide the html code, but I assume it is something like this:

<form method="POST" id="form">
    <input type="hidden" id="data" />
</form>

If that is correct, then you should say $("#data").val(xml); instead of text() or html() as those change the matched thing with text or html you provide. This should work for your current solution.

Also I'd propose to look at jQuery's $.post() and others as an alternative to packing everything as xml unless this is really what you want on the backend. It could be easier to just make up a javascript object with all the values keyed by some names and pass it on to one of jQuery's $.post(), $.get(), etc. like this:

var values = {name: "John", surname: "Doe"};
values.age = 25;
$.post("index.jsp", values); // this will result in a post with 3 variables: name, surname, age

Actually it only occured to me now that you can also send your xml this way (unless you prefer your way of doing things):

$.post("index.jsp", {data: "<xml><whatever-else-needs-to-be-in-here/></xml>"});

You might want to enlighten yourself more here: Ajax @ jQuery docs

like image 195
inkredibl Avatar answered Sep 28 '22 19:09

inkredibl