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.
Set the content type
$.ajax({
type: "POST",
contentType: "application/xml", //or text/xml?
url: "http://localhost:8080/MyWebApp/MyWebAppUrl",
data: xml
});
Add processData: false to your call and it should leave the string alone...
$.ajax({
type: "POST",
contentType: "application/xml", //or text/xml?
url: "http://localhost:8080/MyWebApp/MyWebAppUrl",
data: xml,
processData: false
});
Related
In my ASP.NET site, I use Jquery AJAX to load json data (in fact a string) from a webservice when clicking the search button :
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(parameterArray),
contentType: "application/json",
dataType: "json",
success: function(response) {
d = JSON.parse(response.d);
}
When the return string gets too big, the page stop responding. I have to go to web.config and add this property in order for the website to work :
<jsonSerialization maxJsonLength="2147483644"/>
Here is how do the application handle the search result before returning data to the browser :
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue;
string strData = dService.searhforData(ipt);
List<Dictionary<string, object>> lRow = processData(strData);
string r = serializer.Serialize(lRow);
return r;
In case the Json string got too long, the page just stop responding, there wasn't any error in the console window. As I debug at the .Net application side, the serializer.Serialize(lRow); went smoothly and successfully return the r, after that, the loading icon on the page just keep spinning. If I press F5 on the page, the search data appears.
My question is, if JQuery's Ajax refers to the web.config for the max json string length, why couldn't I find any information regarding this on the internet ?
I'm sure there is a limit on the amount of data that JSON.parse() can handle, but that's not related to your problem.
Your web.config file holds settings to be used server side. The JS on the client is not related to that at all. If you needed to amend that setting it's because your ASP.Net code was producing a JSON response longer than was previously allowed by the default setting of jsonSerialization.
If you checked the browser console after making the failed request you would most likely have seen an error in the response which guided you to the problem.
I am trying to access some content on a web page that is created by some Javascript. However, the content that I wish to access is created by the javascript after the page has loaded so this chunk of Html source is no where to be found when I try and parse it with Jsoup.
My code for getting the Html source, using HtmlUnit is as follows:
public static void main(String[] args) throws IOException {
java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(java.util.logging.Level.OFF);
WebClient webClient = new WebClient(BrowserVersion.CHROME);
webClient.getOptions().setThrowExceptionOnScriptError(false);
webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
String url = "myUrl.com";
out.println("accessing " + url);
HtmlPage page = webClient.getPage(url);
out.println("waiting for js");
webClient.waitForBackgroundJavaScriptStartingBefore(200);
webClient.waitForBackgroundJavaScript(20000);
out.println(page.asXml());
webClient.close();
}
But when I run it, the Html that is supposed to be created is not printed. I was wondering how do I get this Html source, created by the Javascript, using HtmlUnit and then getting said result and passing it to Jsoup for parsing?
Jsoup is server side processing framework,
I am not sure what is your final goal, I assume you want to use it in the same page so I will go with Ajax so you can do:
On document ready, capture the document dom
Send it for processing on server side
Display the results on the same page
Something like:
.
$( document ).ready(function() {
var allClientSideHtml = $("html").html();
var dataToSend = JSON.stringify({'htmlSendToSever':allClientSideHtml });
$.ajax({ url: "your_Jsoup_server_url.jsp_or_php/YourJsoupParser",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: dataToSend , // pass that text to the server as a JSON String
success: function (msg) { alert(msg.d); },
error: function (type) { alert("ERROR!!" + type.responseText); }
});
});
Anybody know the correct syntax for updating a row in Google Spreadsheets using the Javascript API?
I'm working off of the API documentation here and I can't figure out what is the correct syntax I need to send the data in. What I have currently is:
var serialObject = $('#basicForm').serialize();
$.ajax({
url: updateBasicUrl,
type: 'PUT',
data: serialObject,
});
What should the syntax of the data field be (the above throws an unidentifiable error)?
EDIT - after converting a JSON object to XML to conform to the exact look of the xml here, it still doesn't work:
var updateBasicUrl = "https://spreadsheets.google.com/feeds/list/*spreadsheetIDnumber*/od6/private/full/*cellID*/*versionnumber*?access_token=*accesstoken*
$.ajax({
url: updateBasicUrl,
type: 'PUT',
contentType: 'application/atom+xml',
//contentType: 'text/xml', //tried both of these, they don't seem to work
data: xmlBasic,
})
EDIT - So it seems there is a Cross-Domain Origin problem. The Google Spreadsheets API won't allow it. Anybody know of a work-around?
you could search the java source code for the solution - http://code.google.com/p/gdata-java-client/source/browse/trunk/java/src/com/google/gdata/client/spreadsheet/SpreadsheetService.java?r=94
this triggers the send in the java version:
service.insert(cellFeedUrl, newEntry);
public void setCell(int row, int col, String formulaOrValue)
throws IOException, ServiceException {
CellEntry newEntry = new CellEntry(row, col, formulaOrValue);
service.insert(cellFeedUrl, newEntry);
out.println("Added!");
}
My requirement is whenever a Image is clicked a PDF should be opened on the browser. I am using Jquery ajax [POST call] to make a call to the ASP.NET MVC side and a file is returned on the response. A POST is required from the jquery side since I need to pass substantial data from client to server.
HTML Part:
<span data-id='printSettings' title='Generate PDF' class="preferenceSettings"></span>
JS Part: This is fired when the Generate PDF icon is clicked.
var textToSend = $('.microChartTable', self.element)[0];
var dataToSend = { htmlContent: textToSend.outerHTML };
$.ajax({
url: "/EADashboard/ConvertToPDF",
data: JSON.stringify(dataToSend),
type: 'POST',
contentType: 'application/json',
success: function (data) {
} // -- success ends here
});
ASP.NET Side : In my controller, I have the following code:
[HttpPost]
public FileResult ConvertToPDF(HtmContent content)
{
string fileName = Server.MapPath("~/SeedData/data.pdf");
string contentType = "application/pdf";
return new FilePathResult(fileName, contentType);
}
Now the PDF generation code is correct just that the PDF file is not been opened on the browser side. I have seen the post Return PDF to browser using JSON and MVC? but since there was no solution provided, I am posting this again. Can anyone let me know how this can be achieved ?
Thanks
Two things.
Why are you doing post via ajax and not a regular post? With a regular post your code would probably work.
If you indeed need to do it with ajax, you are receiving result in the data object on the success of the ajax call, and I do not see that you do anything with it, which is why you do not see anything happening.
I am using Open Flash Chart 2 to create some graphs. I want to be able to save an image of the graph, which OFC2 supplies some methods to accomplish this. I used the example on the OFC2 site to directly display the raw image data on the page, but that does not work in IE6, which most of our users are using (I know, I know).
I switched to using the OFC2 method, post_image to post the raw image data to the server. I use a Perl script to receive the image data, save it to a file, and I can view the image. The unfortunate part about using the post_image method is that ActionScript throws an error when saving the image:
Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs.
Which apparently is a bug in Adobe - see this page. Because of this error, the post_image method does not complete successfully, so the javascript callback won't ever fire - I basically don't have a way to tell if the image was saved successfully.
So, I thought I would use the get_img_binary method of OFC2 to get the binary data of the image, and use jQuery to post the binary data to my Perl script.
I cannot figure out how to send the binary data correctly, or how to let my Perl script receive the binary data correctly, or both.
Here is my jQuery function:
var chartObj = $("#chart_object").get(0);
$.ajax({
type: "POST",
url: 'download_image.pl',
//contentType: 'application/octet-stream',
contentType: 'image/png',
//processData: false,
//data: { imgData: chartObj.get_img_binary() },
data: chartObj.get_img_binary(),
dataType: "text",
success: function(data) {
console.log( data );
}
});
You can see from some of my commented out lines that I have tried various contentTypes and other settings of the Ajax call.
The Ajax call is sending some data, but it doesn't appear to be binary. I think it is a base64 representation of the binary data.
Does anyone have any ideas on how to send binary data from javascript to the server?
The Perl script I have works fine for the post_image method, so I don't think the problem is there?
Thanks in advance!
I seem to have stumbled onto the solution.
Here is my ajax call:
var chartObj = $("#chart_object").get(0);
$.ajax({
type: "POST",
url: 'download_image.pl',
contentType: 'application/octet-stream',
processData: false,
data: imgData,
dataType: "text",
success: function(data) {
console.log( data );
}
});
And here is my Perl snippet to process/save the image:
use CGI qw(:standard);
use MIME::Base64;
...
my $img64 = param('POSTDATA');
my $img = decode_base64( $img64 );
...
#then print $img out to a file in binary mode
I had to decode the base64 representation of the PNG file, and then save it to a file.
i've got trouble too with using IE6 and OFC2 for saving image... So here are the scripts i use (javascript + PHP)
i know it's not very beautifull but jQuery doesn't want to work in a popup created via window.open('') on my IE6 so i decided to use a "old school method" to get it...
// javascript in the page displaying the flash chart
OFC = {};
OFC.jquery = {
name: "jQuery",
image: function(src) { return '<img src="data:image/png;base64,' + $('#'+src)[0].get_img_binary() + '" \/>'},
popup: function(src) {
var img_tag = OFC.jquery.image(src);
var img_win = window.open('', 'imagesave');
img_win.document.write('<html><head><title>imagesave<\/title><\/head><body>'+ img_tag + '<\/body><\/html>');
img_win.document.close();
},
popupie: function(src) {
var img_data = "image/png;base64,"+$("#"+src)[0].get_img_binary();
var img_win = window.open('', 'imagesave');
with(img_win.document) {
write('<html>');
write('<head>');
write('<title>imagesave<\/title>');
write('<\/head>');
write('<body onload="document.forms[0].submit()">');
write('<form action="\/ofc\/base64post.php" method="post">');
write('<input type="hidden" name="d" id="data" value="'+img_data+'" \/>');
write('<\/form>');
write('<div><img src="\/ofc\/ajax-loader.gif" border="0" alt="" \/><\/div>');
write('<div style="font-family: Verdana;">Please wait<br \/>After you can save the image<\/div>');
write('<\/body>');
write('<\/html>');
}
img_win.document.close();
}
}
function save_image() { // this function is automatically called
if ($.browser.msie)
OFC.jquery.popupie("my_chart"); // only for IE navigators
else
OFC.jquery.popup("my_chart"); // for the others
}
so, when we use the save_image() function (which is automaticaly called when you right clic dans select "Save Image Locally" on the flahs chart)
the image of the chart is tranfered to the popup and the data (base64 binary image) are posted to a php script /ofc/base64post.php that rander the picture :
<?php
// base64post.php
$data = split(';', $_POST['d']);
$type = $data[0];
$data64 = split(',', $data[1]);
$pic = base64_decode($data64[1]);
header("Content-type: $type");
echo $pic;
?>
hope that help someone !