I'm having some problems posting data from a web page, using jQuery, to a servlet. While I'm an experienced Java developer, I'm very new to javascript/jQuery/servlets. I'm using Eclipse, Apache Tomcat, and Chrome.
I have an XML file (from 6KB to 30MB in size) that I wish to load into the browser, modify, then post to the servlet.
My HTML has:
<input id="filechooser" type="file" onchange="readFile()">
My JS has:
var file = document.getElementById('filechooser').files[0];
var reader;
reader = new FileReader();
reader.readAsText(file, "UTF-8");
reader.onload = loaded;
function loaded(evt){
var result = evt.target.result;
var xml = $(result);
...
[make modifications to xml]
}
Some jQuery code that I use in modifying the xml are $(xml).find("NODE").val()
and $(xml).find("OTHER_NODE").attr("attribute-name","newValue")
I now need to post that xml to a URL, where it will be used to process some information. In the Chrome console, I can view the content of the xml object:
> xml
[<!--?xml version="1.0" encoding="ISO-8859-1"?-->,#text,
<root_element>...</root_element>]
> $(xml)
[<!--?xml version="1.0" encoding="ISO-8859-1"?-->,#text,
<root_element>...</root_element>]
> console.dir(xml)
jQuery.fn.jQuery.init[3]
0: #comment
1: #text
2: root_element
length: 3
__proto__: Object[0]
My servlet is empty so far:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Post");
}
I created a button that executes some javascript. The following two code snippets both post to the server:
$.post("http://localhost:8080/MyWebApp/MyWebAppUrl", xml);
and:
$.ajax({
type: "POST",
url: "http://localhost:8080/MyWebApp/MyWebAppUrl",
data: xml
});
My problem is, I don't know if I'm sending my XML correctly, or how to properly consume it. What do I need to do to my jQuery code to post it correctly? How do I get it out of my HttpServletRequest? If I can get the xml text as a String, I know exactly how to manipulate it in Java, and get it to do whatever I want.
After 10+ hours searching the web, I still can't find the answer. I'm sure it's out there, but I can't seem to connect the dots.
UPDATE:
epascarello was spot on for posting an XML document. However, I was parsing the document incorrectly.
Notice that I read the file, then stored the result var xml = $(result)
. The file was read as a text string, and I was converting it to an HTML document.
What I needed to do was var xml = jQuery.parseXML(result)
. That way, I didn't have to convert it back to a text string, and tag capitalizing is maintained.
Note that maintaining capitalization is of critical important.