views:

3621

answers:

3

Hi, 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 submiting the form, sending with $.post and a few more jquery functions but nothing worked. Any ideas?

in my JSP im reading the post like this:

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

This doesnt work:

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

This either:

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

replacing .text with .html doesnt work

Any ideas are welcome, thx

+1  A: 

You could always use an XMLHttpRequest to send the data. This can be done with our without user interaction on an element such as a form submit button. jQuery has functionality built in for assisting with such requests.

http://docs.jquery.com/Ajax

Adam Peck
Suggesting another library is like creating a mess here. JQuery is as good as Prototype in making AJAX calls, if not better.
Adeel Ansari
+1  A: 

Trying using the jQuery Ajax API - you can use it to send arbitrary data via GET or POST and you don't need to set up a hidden form or anything.

Marc Novakowski
Yes, we don't submit forms, like we traditionally do. A sound suggestion.
Adeel Ansari
+2  A: 

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

inkredibl