I was implementing an interface with uses DataTables and excel files. Motive is upload an excel and then show it in DataTables.
As I didn't find any javascript library which parse the excel and provide it to DataTables. The only option is ot send the data to the front end struts/ java and send back the json.
Is it possible to have DataTables waiting for the json by Ajax without sending the request. .
i think, it is possible in html5 and javascript. run and test the code below.
<html>
</head>
<script>
function readBlob() {
var files = document.getElementById('files').files;
if (!files.length) {
alert('Please select a file!');
return;
}
var file = files[0];
var start = 0;
var stop = file.size;
var reader = new FileReader();
// If we use onloadend, we need to check the readyState.
reader.onloadend = function(evt) {
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
document.getElementById('byte_content').textContent = evt.target.result;
}
};
var blob = file.slice(start, stop);
reader.readAsBinaryString(blob);
}
</script>
</head>
<body>
<input type="file" id="files" name="file" accept=".csv" />
<span class="readBytesButtons">
<button onclick="readBlob()">entire file</button>
</span>
<div id="byte_range"></div>
<div id="byte_content"></div>
</body>
</html>
we can extract the excel data as text by FileReader in javascript.
if you want to display the data in datatable, please apply your logic.
Yes off course,
I think you want to try something like this
upload file to server
read the excel file in strut action, save it on disk in temp folder and return file name to your JSP.
when first step done then make Ajax Call to struts action
pass file name as parameter fom datatable ajax call
load file from disk read it and populate in Pojo or VO object
create Json from Pojo using gosn or jakson api
finally return json.
further see data table ajax source
Yes this is possible, but no Ajax is need in your case. How would i do it? See below:
Have a form to upload the excel file to my struts implementation. Then do the processing of the excel file and return the contents in pure html/table format. Then do a simple datatables initialization on page load and your are finished!
UPDATE
For pagination, datatables support ajax like this:
var oTable = "";
$(document).ready(function() {
oTable = $('#htmltableID').dataTable({
"sPaginationType": "full_numbers",
"bServerSide": true,
"sAjaxSource": "/myAjaxSource.jsp?page="+pageNumber+",
"sServerMethod": "POST",
"iDisplayLength": 50
});
}
Then in your myAjaxSource.jsp you get the parameter page sent by the ajax URL and return the appropriate data (json)
Related
I'm trying to send a JSON object to a JSP to parse. The JavaScript code is:
function sendData(field1, oper1, value1, field2, oper2, value2, field3, oper3, value3){
var formData = {"field1":field1, "oper1":oper1, "value1":value1, "field2":field2, "oper2":oper2, "value2":value2, "field3":field3, "oper3":oper3, "value3":value3};
$.post("<%=request.getRequestURL().toString()%>getInfo.jsp", {formData:formData}, function(response){alertHere(response)});
}
function alertHere(){
window.alert("Post Successful!")
}
My submit button is:
<input type="submit" value="SEARCH" name="submit" class="srchbutton" onclick="sendData(document.getElementById('field1').value, document.getElementById('oper1').value>
There are several more fields passed in the JavaScript button on click, I just didn't want to post that long of a line.
When I try to post with text data in the form, my web developer console flashes the path to my JSP really quickly then disappears. It's too fast to see the error. If there's no data, the post is successful, as my alertHere function in $.post() is called correctly. I'm not sure if I'm missing something.
Assuming you have a servlet on the server side which handles the data you are sending from the jsp page you could create a pseudo-class using javascript, then parses it to json and finally sends it to the server. for example:
javascript and jQuery
function SomeClass (){
this.field1 = $("#field1").val();
this.oper1 = $("#oper1").val();
this.value1 = $("#value1").val();
// etc. for every field you want to send
}
note: i'm assuming every field have an id.
function alertHere(){
window.alert("Post Successful!")
}
jQuery and ajax
$("#someID").click(function(){
event.preventDefault(); <-------- if you replace the submit button for a simple button,
you don't need to do this.
var formData = new SomeClass();
$.ajax({
url:"ServletName",
data: JSON.stringify(formData),
dataType:"json",
}).done(function(response){
alertHere(response);
});
});
html
<input type="submit" value="SEARCH" id="someID" name="submit" class="srchbutton">
Try changing this line of code
$.post("<%=request.getRequestURL().toString()%>getInfo.jsp", {formData:formData}
To
$.post("<%=request.getRequestURL().toString()%>getInfo.jsp", {formData:Json.stringify(formData)}
Not entirely sure if this would work, Just a suggestion.
Figured it out. The problem was that I wasn't passing my "response" to my success function, so:
function alertHere(){
window.alert("Post Successful!")
}
should have been:
function alertHere(response){
window.alert("Post Successful!")
}
It was probably posting correctly, but I wasn't getting a success because the response wasn't getting passed.
I am building an Android app and I want to post a html form that looks like this:
<form onsubmit="ShoutBox.postShout(); $('shout_data').value = ''; return false;">
Shout: <input type="text" id="shout_data" size="50"> -
<input type="submit" value="Shout Now!" id="shouting-status"></form>
I am using Jsoup in the rest of the application and I would preferably use it for this aswell.
I know about the .data(name, value) method, but since the html text and button don't have name attributes, that's not working. I can extract the field by using the ids and fill the field with: Element.val(String val); But I don't know how to post the form after that. Can anyone help me?
This is the JavaScript code for posting it:
postShout: function() {
message = $("shout_data").value;
if (message == "") {
return false;
}
$("shouting-status").value = ShoutBox.lang[0];
postData = "shout_data="+encodeURIComponent(message).replace(/\+/g, "%2B");
new Ajax.Request('xmlhttp.php?action=add_shout', {method: 'post', postBody: postData, onComplete: function(request) { ShoutBox.postedShout(request); }});
},
The post is not done via a form submit and post variables but via JavaScript and an XML HTTP request. JSoup is incapable to execute JavaScript. You need a browser that you can remote control. To do this headless in Java HTMLUnit is a good choice.
I am learning dojo and a begginer. I would like to load and edit a text file from interface using Dojo. Please direct me which component in dojo would suffice this.
From the answer to my comment, my understanding is that you want to:
Enter a file name into a form on your webpage.
Dojo will then load that particular text file from your sever.
The file then needs to be displayed on the screen in some sort of editing componant.
The user then needs the facility to post the file back to the server.
I would have thought that the best approach is to use dojo/request to get the text file and then use it again to post it back. You could the various dojo dijits to do the selecting and displaying.
A very crude solution would be:
<form data-dojo-type="dijit/form/Form">
<input type="text" id="fileName" data-dojo-type="dijit/form/TextBox" />
<button data-dojo-type="dijit/form/Button" type="button">Get
<script type="dojo/on" data-dojo-event="click">
require([
"dijit/registry",
"dojo/request"
], function(registry, request) {
var fileName = registry.byId("fileName").get("value");
request(fileName, {
"handleAs": "text"
}).then(function(content){
registry.byId("content").set("value", content);
});
});
</script>
</button><br /><br />
<textarea id="content" data-dojo-type="dijit/form/TextBox"></textarea>
<button data-dojo-type="dijit/form/Button" type="button">Send
<script type="dojo/on" data-dojo-event="click">
require([
"dijit/registry",
"dojo/request"
], function(registry, request) {
var content = registry.byId("content").get("value");
request("myhandler.php", {
"method": "post",
"data": {
"content": content
}
}).then(function(content){
// deal with the response
});
});
</script>
</button>
</form>
This will load a text file with the filename you enter in the text box (after clicking get). The content is loaded into the textarea for editing and can be sent back to a server script by clicking send.
This is as I said, "a very crude example". However, it shows the use of dojo/request to receive and post information to/from the server. Obviously, you'd want a more sophisticated solution that hides/shows widgets at the appropriate moment. You would probably want to replace the filename textbox with a some sort of combo populated via your server code...etc, etc.
I'd suggest you write your own widget to encapsulate the whole operation, rather than declare it all in markup. You could use dojo/request to load a json file from the server to populate a combo box to select the file. You'd also want to ensure the information being posted back is from a trusted source.
Important! This will only work if the textfile and you webpage are residing on the same domain. It will not work for cross-domain requests. If you want to do cross-domain you'll need to create a json solution.
I have tried different things but i am not able to do this.
I am very new to jquery json and ajax. I wrote a servlet which connects to my databse and retrive user ids from the table. I wrote a jsp and which has a text box that takes input text and refines the results on each key press I want to do it in a html page using jquery ajax by sending json object from my servlet. can someone give me an example for this scenario.
Thanks in advance.
http://jsfiddle.net/tAjNz/
<input type="text" />
<select id="autoPop" multiselect="true"></select>
<script>
// define a data source (ajax or on page load);
myJson = [{value:1,text:'Item One'},{value:1,text:'Item Two'},{value:1,text:'Item Three'},{value:1,text:'Item Four'}];
$('input[type="text"]').keyup(function(){
//Optionally update the data source when a user starts typing or use the predefined source.
//Populate the select list
$sel = $('select');
$sel.html('');
var $this = $(this);
$.each(myJson,function(k,v){
if(v.text.toLowerCase().indexOf($this.val().toLowerCase()) > -1) {
$sel.append('<option value="' + v.value+ '">'+ v.text+'</option>');
}
});
});
</script>
I retrieved a blob along with some other data from a table, say name and image:
name = varchar, image = blob
I set this to an object in my filter and pass it to the JSP file:
request.setAttribute("info", object);
In the JSP file I get that data:
request.getAttribute("info");
Now that I have the data from that object how do I go about passing that info to my JS file and render the image as a source for the JS file?
I'm trying:
<div>
<script type="text/javascript" src="jsFile.js></script>
</div>
var name = <%=info.name%>;
var image = <%=info.image%>
It just doesn't seem to be working. What is the correct method of doing this?
This isn't going to work. Leave the blob there in the server side. JavaScript on the client side can't do anything sensible with binary data. All it needs is an URL of the image so that it can reference it in the src attribute of a HTML <img> element, so that the webbrowser can in turn do its job of downloading and displaying the image. Best would be to include the image identifier in the URL. The name is unique for the image, right? Use that in the URL instead.
The first step is to let JS create a HTML <img> element with the proper src attribute which points to an URL which returns the image. Assuming that you're preparing the data like follows
String name = "foo.png";
String imageURL = "imageservlet/" + name;
request.setAttribute("imageURL", imageURL);
and are printing it in JSP(!) as if it are JS variables as follows
<script>
var imageURL = '${imageURL}';
// ...
</script>
(please note that those singlequotes are thus mandatory to represent them as a JS string variable)
so that they end up in the generated HTML source like follows (rightclick page in browser and do View Source to verify it)
<script>
var imageURL = 'imageservlet/foo.png';
// ...
</script>
then you can create the image as follows
var img = document.createElement("img"); // or getElementById("someId")?
img.src = imageURL;
// ... add to document?
(please note that this is just an example, I have no utter idea what the functional requirement is and what you would like to do with this image element, even more, perhaps JS code isn't needed at all for the concrete functional requirement)
so that it ends up like this in HTML:
<img src="imageservlet/foo.png" />
Now, the second step is to create a servlet which listens on an URL pattern of /imageservlet/*, retrieves the image as an InputStream from the database by the passed-in indentifier and writes it to the OutputStream of the response along a set of correct response headers. Long story short, I've posted several answers before as to how to do it, they contains kickoff code snippets:
How to retrieve and display images from a database in a JSP page?
Writing image to servlet response with best performance
You can access your data from the script if you set the variables in a script block before your jsFile.js. Ie:
<div>
<script type="text/javascript">
var name = <%=info.name%>;
var image = <%=info.image%>;
</script>
<script type="text/javascript" src="jsFile.js></script>
</div>
I'm not sure how you intend to handle the binary (BLOB) image data however? Typically this would be written to an image file on the server and referenced via an img tag:
<img src="/path/to/myimage.jpg" />
Instead of passing your blob data to the JSP file, I would suggest having the server (your servlet) pass a URL to the JSP which the browser can use to get the image via an img tag. You can either write the blob data to a URL or write a servlet that writes out Content-type: image/jpeg (or similar) data when passed an id, ie:
<img src="http://www.yourserver.com/GetImage?imageId=xxx" />