How do I know if form submission is successful? - java

I have a form, basically to upload a file. I am submitting the form twice, 1 without multipart and the 2nd 1 with multipart.
<input type="button" tabindex="5" value="Create" id="btnS" class="btn" onClick="submitForm(this.form,'/test/upload'); return false;" />
//1st submission
form.setAttribute("action",url_action);
form.setAttribute("method","post");
form.submit();
//2nd submission
form.setAttribute("action",url_action);
form.setAttribute("method","post");
form.setAttribute("enctype","multipart/form-data");
form.setAttribute("encoding","multipart/form-data");
form.submit();
but instead I want to 1st check if the 1st form submission is successful then go for 2nd submition
Edited after referring #Vern
var postString = getPostString();
var client=new XMLHttpRequest();
client.onreadystatechange=handler(form,url_action);
client.open("POST",url_action,true);
client.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
client.setRequestHeader("Content-length", postString.length);
client.setRequestHeader("Connection", "close");
client.send(postString);
function handler(form,url_action)
{
if(this.readyState == 4 && this.status == 200) {
//Here submitted is the text that I receive from the servlet If 1st submit is successful
if (xmlhttp.responseText == "submitted"){
secondSend(form,url_action);
} else {
alert("Not good!");
}
}
}
function getPostString()
{
}
function secondSend(form,url_action)
{
form.setAttribute("action",url_action);
form.setAttribute("method","post");
form.setAttribute("enctype","multipart/form-data");
form.setAttribute("encoding","multipart/form-data");
form.submit();
}
Here is my servlet part. where I am identifying if its multipart or not. If not store the resultType to a session variable then return submitted,
Now I want to check for this "submitted" or similar and go for submitting the form 2nd time.
2nd Form submission: Here I will check if its multipart again, and check the session variable and go for CRUD. (This IdentifyNow is basically a kind of request modulator)
public String identifyNow()throws ServletException, java.io.IOException
{
UploadXmlAgent uploadAgent;
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
System.out.println("\n\n*********************************\nisMultipart: "+isMultipart);
if(isMultipart)
{
session=request.getSession(false);
System.out.println("\nThis is multipart and isNew"+session.isNew());
if(session!=null)
{
System.out.println("\ninside session");
requestType=session.getAttribute("resultType").toString();
//Identified based on requestType, instantiate appropriate Handler
//session.invalidate();
if(requestType.equals("Create"))
{
uploadAgent=new UploadXmlAgent(realPath,request,paramMap);
uploadAgent.retrieveXml();
return uploadAgent.uploadXml();
}
else if(requestType.equals("Update"))
{
}
else if(requestType.equals("Delete"))
{
}
}
else
{
return "Session is null";
}
}
else
{
System.out.println("\nNot a multipart");
paramMap=request.getParameterMap();
if (paramMap == null)
throw new ServletException(
"getParameterMap returned null in: " + getClass().getName());
iterator=paramMap.entrySet().iterator();
System.out.println("\n"+paramMap.size());
while(iterator.hasNext())
{
Map.Entry me=(Map.Entry)iterator.next();
if(me.getKey().equals("resultType"))
{
String[] arr=(String[])me.getValue();
requestType=arr[0];
System.out.println("Inside returntype: "+requestType);
}
}
session=request.getSession(true);
session.setAttribute("returntype", requestType);
System.out.println("Session.isNew="+session.isNew());
return "submitted";
}
return "noCreate";
}
Here is Javascript function which is used to submit form twice, look for micoxUpload() function.
/* standard small functions */
function $m(quem){
return document.getElementById(quem)
}
function remove(quem){
quem.parentNode.removeChild(quem);
}
function addEvent(obj, evType, fn){
// elcio.com.br/crossbrowser
if (obj.addEventListener)
obj.addEventListener(evType, fn, true)
if (obj.attachEvent)
obj.attachEvent("on"+evType, fn)
}
function removeEvent( obj, type, fn ) {
if ( obj.detachEvent ) {
obj.detachEvent( 'on'+type, fn );
} else {
obj.removeEventListener( type, fn, false ); }
}
/* THE UPLOAD FUNCTION */
function micoxUpload(form,url_action,id_element,html_show_loading,html_error_http){
/******
* micoxUpload - Submit a form to hidden iframe. Can be used to upload
* Use but dont remove my name. Creative Commons.
* Versão: 1.0 - 03/03/2007 - Tested no FF2.0 IE6.0 e OP9.1
* Author: Micox - Náiron JCG - elmicoxcodes.blogspot.com - micoxjcg#yahoo.com.br
* Parametros:
* form - the form to submit or the ID
* url_action - url to submit the form. like action parameter of forms.
* id_element - element that will receive return of upload.
* html_show_loading - Text (or image) that will be show while loading
* html_error_http - Text (or image) that will be show if HTTP error.
*******/
//testing if 'form' is a html object or a id string
form = typeof(form)=="string"?$m(form):form;
var erro="";
if(form==null || typeof(form)=="undefined"){ erro += "The form of 1st parameter does not exists.\n";}
else if(form.nodeName.toLowerCase()!="form"){ erro += "The form of 1st parameter its not a form.\n";}
if($m(id_element)==null){ erro += "The element of 3rd parameter does not exists.\n";}
if(erro.length>0) {
alert("Error in call micoxUpload:\n" + erro);
return;
}
//creating the iframe
var iframe = document.createElement("iframe");
iframe.setAttribute("id","micox-temp");
iframe.setAttribute("name","micox-temp");
iframe.setAttribute("width","0");
iframe.setAttribute("height","0");
iframe.setAttribute("border","0");
iframe.setAttribute("style","width: 0; height: 0; border: none;");
//add to document
form.parentNode.appendChild(iframe);
window.frames['micox-temp'].name="micox-temp"; //ie sucks
//add event
var carregou = function() {
removeEvent( $m('micox-temp'),"load", carregou);
var cross = "javascript: ";
cross += "window.parent.$m('" + id_element + "').innerHTML = document.body.innerHTML; void(0); ";
$m(id_element).innerHTML = html_error_http;
$m('micox-temp').src = cross;
//del the iframe
setTimeout(function(){ remove($m('micox-temp'))}, 250);
}
addEvent( $m('micox-temp'),"load", carregou)
//properties of form
/*form.setAttribute("target","micox-temp");
form.setAttribute("action",url_action);
form.setAttribute("method","post");*/
//form.submit();
var postString = getPostString();
var client;
if (window.XMLHttpRequest){ // IE7+, Firefox, Chrome, Opera, Safari
client=new XMLHttpRequest();
} else { // IE6, IE5
client=new ActiveXObject("Microsoft.XMLHTTP");
}
//client.onreadystatechange=handler(form,url_action);
client.open("POST",url_action,true);
client.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
client.setRequestHeader("Content-length", postString.length);
client.setRequestHeader("Connection", "close");
client.onreadystatechange = function(){
if (client.readyState==4 && client.status==200){
alert(client.responseText); //This gives back my text from servlet
secondSend(form,url_action);
}
};
client.send($postStr);
alert("1st request send");
//secondSend(form,url_action);
//while loading
if(html_show_loading.length > 0){
$m(id_element).innerHTML = html_show_loading;
}
function getPostString()
{
$postStr=document.getElementsByTagName("confname");
$postStr+=document.getElementsByTagName("returntype");
return $postStr;
}
function secondSend(form,url_action)
{
form.setAttribute("target","micox-temp");
form.setAttribute("action",url_action);
form.setAttribute("method","post");
form.setAttribute("enctype","multipart/form-data");
form.setAttribute("encoding","multipart/form-data");
form.submit();
if(html_show_loading.length > 0){
$m(id_element).innerHTML = html_show_loading;
}
}
}

submit() does not have a return value and as such you are not able to check the outcome of the submission just based on your code above.
However, the common way to do it is actually to use Ajax and use a function to set a flag. That way, you can check if the form is successfully submitted. Not to mention, with the server reply, you can further validate if the form has been transmitted correctly to the server :)
Hope it helped. Cheers!
The following code should give you an idea of how to do it:
function first_send(){
// Local Variable
var xmlhttp;
// Create Object
if (window.XMLHttpRequest){ // IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
// Set Function
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
// (1) Check reply from server if request has been successfully
// received
// (2) Set flag / Fire-off next function to send
// Example
if (xmlhttp.responseText == "ReceiveSuccess"){
secondSend();
} else {
// Error handling here
}
}
}
// Gets the first set of Data you want to send
var postString = getPostString();
// Send
xmlhttp.open("POST","form1.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", postString.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(postString);
}
And you'll need:
function getPostString(){
// Collect data from your form here
}
function secondSend(){
// You can create this function and post like above
// or just do a direct send like your code did
}
Hope it helps (:
This code ought to do the trick, but be sure to fill up with the HTML form that you're using! Also, put the first form in a submission if you require:
<script type="text/javascript">
var postString = getPostString();
var client = new XMLHttpRequest(); // You shouldn't create it this way.
// Open Connection and set the necessary
client.open("POST",url_action,true);
client.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
client.setRequestHeader("Content-length", postString.length);
client.setRequestHeader("Connection", "close");
// Create function
client.onreadystatechange = function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
if (xmlhttp.responseText == "Success") {
secondSend();
} else {
alert('In Error');
}
}
};
client.send(postString);
function getPostString()
{
// Get your postString data from your form here
// Return your Data to post
return $postStr;
}
function secondSend()
{
// Make sure you fill up your form before you post
form.setAttribute("action",url_action);
form.setAttribute("method","post");
form.setAttribute("enctype","multipart/form-data");
form.setAttribute("encoding","multipart/form-data");
form.submit();
}
</script>

I am sharing the ajax way of doing it apart from the regular XMLHttpRequest by #Vern
/*CALLING 1st SUBMIT*/
$(function() {
$("#submitButton").click(callme);
function callme() {
var form=document.forms["yourFormID"];
$.ajax({
type: "POST",
url: "/upload",
data: {resulttype: $('#resulttype').val()},
async:false,
complete: function(msg){
micoxUpload(form,'/upload','postUploadInformation','Loading...','Crap! something went wrong'); return false;
}
});
}
});
/* THE UPLOAD FUNCTION */
function micoxUpload(form,url_action,id_element,html_show_loading,html_error_http){
/******
* micoxUpload - Submit a form to hidden iframe. Can be used to upload
* Use but dont remove my name. Creative Commons.
* Versão: 1.0 - 03/03/2007 - Tested no FF2.0 IE6.0 e OP9.1
* Author: Micox - Náiron JCG - elmicoxcodes.blogspot.com - micoxjcg#yahoo.com.br
* Parametros:
* form - the form to submit or the ID
* url_action - url to submit the form. like action parameter of forms.
* id_element - element that will receive return of upload.
* html_show_loading - Text (or image) that will be show while loading
* html_error_http - Text (or image) that will be show if HTTP error.
*******/
//testing if 'form' is a html object or a id string
form = typeof(form)=="string"?$m(form):form;
var erro="";
if(form==null || typeof(form)=="undefined"){ erro += "The form of 1st parameter does not exists.\n";}
else if(form.nodeName.toLowerCase()!="form"){ erro += "The form of 1st parameter its not a form.\n";}
if($m(id_element)==null){ erro += "The element of 3rd parameter does not exists.\n";}
if(erro.length>0) {
alert("Error in call micoxUpload:\n" + erro);
return;
}
//creating the iframe
var iframe = document.createElement("iframe");
iframe.setAttribute("id","micox-temp");
iframe.setAttribute("name","micox-temp");
iframe.setAttribute("width","0");
iframe.setAttribute("height","0");
iframe.setAttribute("border","0");
iframe.setAttribute("style","width: 0; height: 0; border: none;");
//add to document
form.parentNode.appendChild(iframe);
window.frames['micox-temp'].name="micox-temp"; //ie sucks
//add event
var carregou = function() {
removeEvent( $m('micox-temp'),"load", carregou);
var cross = "javascript: ";
cross += "window.parent.$m('" + id_element + "').innerHTML = document.body.innerHTML; void(0); ";
$m(id_element).innerHTML = html_error_http;
$m('micox-temp').src = cross;
//del the iframe
setTimeout(function(){ remove($m('micox-temp'))}, 250);
}
addEvent( $m('micox-temp'),"load", carregou)
secondSend(form,url_action);
//while loading
if(html_show_loading.length > 0){
$m(id_element).innerHTML = html_show_loading;
}
function secondSend(form,url_action)
{
form.setAttribute("target","micox-temp");
form.setAttribute("action",url_action);
form.setAttribute("method","post");
form.setAttribute("enctype","multipart/form-data");
form.setAttribute("encoding","multipart/form-data");
form.submit();
if(html_show_loading.length > 0){
$m(id_element).innerHTML = html_show_loading;
}
}
}

Related

export multiple pdf files for multiple list using JasperPrint in java [duplicate]

I am not sure if this is possible using standard web technologies.
I want the user to be able to download multiple files in a single action. That is click check boxes next to the files, and then get all the files that were checked.
Is it possible - if so what basic strategy do you recommend. I know I can use comets technology to create server side events that trigger an HttpResponse but I am hoping there is a simpler way.
var links = [
'https://s3.amazonaws.com/Minecraft.Download/launcher/Minecraft.exe',
'https://s3.amazonaws.com/Minecraft.Download/launcher/Minecraft.dmg',
'https://s3.amazonaws.com/Minecraft.Download/launcher/Minecraft.jar'
];
function downloadAll(urls) {
var link = document.createElement('a');
link.setAttribute('download', null);
link.style.display = 'none';
document.body.appendChild(link);
for (var i = 0; i < urls.length; i++) {
link.setAttribute('href', urls[i]);
link.click();
}
document.body.removeChild(link);
}
<button onclick="downloadAll(window.links)">Test me!</button>
HTTP does not support more than one file download at once.
There are two solutions:
Open x amount of windows to initiate the file downloads (this would be done with JavaScript)
preferred solution create a script to zip the files
You can create a temporary set of hidden iframes, initiate download by GET or POST inside of them, wait for downloads to start and remove iframes:
<!DOCTYPE HTML>
<html>
<body>
<button id="download">Download</button>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript">
$('#download').click(function() {
download('http://nogin.info/cv.doc','http://nogin.info/cv.doc');
});
var download = function() {
for(var i=0; i<arguments.length; i++) {
var iframe = $('<iframe style="visibility: collapse;"></iframe>');
$('body').append(iframe);
var content = iframe[0].contentDocument;
var form = '<form action="' + arguments[i] + '" method="GET"></form>';
content.write(form);
$('form', content).submit();
setTimeout((function(iframe) {
return function() {
iframe.remove();
}
})(iframe), 2000);
}
}
</script>
</body>
</html>
Or, without jQuery:
function download(...urls) {
urls.forEach(url => {
let iframe = document.createElement('iframe');
iframe.style.visibility = 'collapse';
document.body.append(iframe);
iframe.contentDocument.write(
`<form action="${url.replace(/\"/g, '"')}" method="GET"></form>`
);
iframe.contentDocument.forms[0].submit();
setTimeout(() => iframe.remove(), 2000);
});
}
This solution works across browsers, and does not trigger warnings. Rather than creating an iframe, here we creates a link for each file. This prevents warning messages from popping up.
To handle the looping part, we use setTimeout, which is necessary for it to work in IE.
Update 2021: I am aware that the "run code snippet" no longer works, but that's due to cross site cookie issues. The code works fine if deployed on your own site.
/**
* Download a list of files.
* #author speedplane
*/
function download_files(files) {
function download_next(i) {
if (i >= files.length) {
return;
}
var a = document.createElement('a');
a.href = files[i].download;
a.target = '_parent';
// Use a.download if available, it prevents plugins from opening.
if ('download' in a) {
a.download = files[i].filename;
}
// Add a to the doc for click to work.
(document.body || document.documentElement).appendChild(a);
if (a.click) {
a.click(); // The click method is supported by most browsers.
} else {
$(a).click(); // Backup using jquery
}
// Delete the temporary link.
a.parentNode.removeChild(a);
// Download the next file with a small timeout. The timeout is necessary
// for IE, which will otherwise only download the first file.
setTimeout(function() {
download_next(i + 1);
}, 500);
}
// Initiate the first download.
download_next(0);
}
<script>
// Here's a live example that downloads three test text files:
function do_dl() {
download_files([
{ download: "https://stackoverflow.com/robots.txt", filename: "robots.txt" },
{ download: "https://www.w3.org/TR/PNG/iso_8859-1.txt", filename: "standards.txt" },
{ download: "http://qiime.org/_static/Examples/File_Formats/Example_Mapping_File.txt", filename: "example.txt" },
]);
};
</script>
<button onclick="do_dl();">Test downloading 3 text files.</button>
The following script done this job gracefully.
var urls = [
'https://images.pexels.com/photos/432360/pexels-photo-432360.jpeg',
'https://images.pexels.com/photos/39899/rose-red-tea-rose-regatta-39899.jpeg'
];
function downloadAll(urls) {
for (var i = 0; i < urls.length; i++) {
forceDownload(urls[i], urls[i].substring(urls[i].lastIndexOf('/')+1,urls[i].length))
}
}
function forceDownload(url, fileName){
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = function(){
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL(this.response);
var tag = document.createElement('a');
tag.href = imageUrl;
tag.download = fileName;
document.body.appendChild(tag);
tag.click();
document.body.removeChild(tag);
}
xhr.send();
}
Easiest way would be to serve the multiple files bundled up into a ZIP file.
I suppose you could initiate multiple file downloads using a bunch of iframes or popups, but from a usability standpoint, a ZIP file is still better. Who wants to click through ten "Save As" dialogs that the browser will bring up?
A jQuery version of the iframe answers:
function download(files) {
$.each(files, function(key, value) {
$('<iframe></iframe>')
.hide()
.attr('src', value)
.appendTo($('body'))
.load(function() {
var that = this;
setTimeout(function() {
$(that).remove();
}, 100);
});
});
}
I agree that a zip file is a neater solution... But if you have to push multiple file, here's the solution I came up with. It works in IE 9 and up (possibly lower version too - I haven't tested it), Firefox, Safari and Chrome. Chrome will display a message to user to obtain his agreement to download multiple files the first time your site use it.
function deleteIframe (iframe) {
iframe.remove();
}
function createIFrame (fileURL) {
var iframe = $('<iframe style="display:none"></iframe>');
iframe[0].src= fileURL;
$('body').append(iframe);
timeout(deleteIframe, 60000, iframe);
}
// This function allows to pass parameters to the function in a timeout that are
// frozen and that works in IE9
function timeout(func, time) {
var args = [];
if (arguments.length >2) {
args = Array.prototype.slice.call(arguments, 2);
}
return setTimeout(function(){ return func.apply(null, args); }, time);
}
// IE will process only the first one if we put no delay
var wait = (isIE ? 1000 : 0);
for (var i = 0; i < files.length; i++) {
timeout(createIFrame, wait*i, files[i]);
}
The only side effect of this technique, is that user will see a delay between submit and the download dialog showing. To minimize this effect, I suggest you use the technique describe here and on this question Detect when browser receives file download that consist of setting a cookie with your file to know it has started download. You will have to check for this cookie on client side and to send it on server side. Don't forget to set the proper path for your cookie or you might not see it. You will also have to adapt the solution for multiple file download.
Angular solution:
HTML
<!doctype html>
<html ng-app='app'>
<head>
<title>
</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
</head>
<body ng-cloack>
<div class="container" ng-controller='FirstCtrl'>
<table class="table table-bordered table-downloads">
<thead>
<tr>
<th>Select</th>
<th>File name</th>
<th>Downloads</th>
</tr>
</thead>
<tbody>
<tr ng-repeat = 'tableData in tableDatas'>
<td>
<div class="checkbox">
<input type="checkbox" name="{{tableData.name}}" id="{{tableData.name}}" value="{{tableData.name}}" ng-model= 'tableData.checked' ng-change="selected()">
</div>
</td>
<td>{{tableData.fileName}}</td>
<td>
<a target="_self" id="download-{{tableData.name}}" ng-href="{{tableData.filePath}}" class="btn btn-success pull-right downloadable" download>download</a>
</td>
</tr>
</tbody>
</table>
<a class="btn btn-success pull-right" ng-click='downloadAll()'>download selected</a>
<p>{{selectedone}}</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="script.js"></script>
</body>
</html>
app.js
var app = angular.module('app', []);
app.controller('FirstCtrl', ['$scope','$http', '$filter', function($scope, $http, $filter){
$scope.tableDatas = [
{name: 'value1', fileName:'file1', filePath: 'data/file1.txt', selected: true},
{name: 'value2', fileName:'file2', filePath: 'data/file2.txt', selected: true},
{name: 'value3', fileName:'file3', filePath: 'data/file3.txt', selected: false},
{name: 'value4', fileName:'file4', filePath: 'data/file4.txt', selected: true},
{name: 'value5', fileName:'file5', filePath: 'data/file5.txt', selected: true},
{name: 'value6', fileName:'file6', filePath: 'data/file6.txt', selected: false},
];
$scope.application = [];
$scope.selected = function() {
$scope.application = $filter('filter')($scope.tableDatas, {
checked: true
});
}
$scope.downloadAll = function(){
$scope.selectedone = [];
angular.forEach($scope.application,function(val){
$scope.selectedone.push(val.name);
$scope.id = val.name;
angular.element('#'+val.name).closest('tr').find('.downloadable')[0].click();
});
}
}]);
working example: https://plnkr.co/edit/XynXRS7c742JPfCA3IpE?p=preview
To solve this, I created a JS library to stream multiple files directly into a zip on the client-side. The main unique feature is that it has no size limits from memory (everything is streamed) nor zip format (it uses zip64 if the contents are more than 4GB).
Since it doesn't do compression, it is also very performant.
Find "downzip" it on npm or github!
This works in all browsers (IE11, firefox, Edge, Chrome and Chrome Mobile) My documents are in multiple select elements. The browsers seem to have issues when you try to do it too fast... So I used a timeout.
//user clicks a download button to download all selected documents
$('#downloadDocumentsButton').click(function () {
var interval = 1000;
//select elements have class name of "document"
$('.document').each(function (index, element) {
var doc = $(element).val();
if (doc) {
setTimeout(function () {
window.location = doc;
}, interval * (index + 1));
}
});
});
This is a solution that uses promises:
function downloadDocs(docs) {
docs[0].then(function (result) {
if (result.web) {
window.open(result.doc);
}
else {
window.location = result.doc;
}
if (docs.length > 1) {
setTimeout(function () { return downloadDocs(docs.slice(1)); }, 2000);
}
});
}
$('#downloadDocumentsButton').click(function () {
var files = [];
$('.document').each(function (index, element) {
var doc = $(element).val();
var ext = doc.split('.')[doc.split('.').length - 1];
if (doc && $.inArray(ext, docTypes) > -1) {
files.unshift(Promise.resolve({ doc: doc, web: false }));
}
else if (doc && ($.inArray(ext, webTypes) > -1 || ext.includes('?'))) {
files.push(Promise.resolve({ doc: doc, web: true }));
}
});
downloadDocs(files);
});
By far the easiest solution (at least in ubuntu/linux):
make a text file with the urls of the files to download (i.e. file.txt)
put the 'file.txt' in the directory where you want to download the files
open the terminal in the download directory from the previous lin
download the files with the command 'wget -i file.txt'
Works like a charm.
To improve on #Dmitry Nogin's answer: this worked in my case.
However, it's not tested, since I am not sure how the file dialogue works on various OS/browser combinations. (Thus community wiki.)
<script>
$('#download').click(function () {
download(['http://www.arcelormittal.com/ostrava/doc/cv.doc',
'http://www.arcelormittal.com/ostrava/doc/cv.doc']);
});
var download = function (ar) {
var prevfun=function(){};
ar.forEach(function(address) {
var pp=prevfun;
var fun=function() {
var iframe = $('<iframe style="visibility: collapse;"></iframe>');
$('body').append(iframe);
var content = iframe[0].contentDocument;
var form = '<form action="' + address + '" method="POST"></form>';
content.write(form);
$(form).submit();
setTimeout(function() {
$(document).one('mousemove', function() { //<--slightly hacky!
iframe.remove();
pp();
});
},2000);
}
prevfun=fun;
});
prevfun();
}
</script>
I am looking for a solution to do this, but unzipping the files in javascript was not as clean as I liked. I decided to encapsulate the files into a single SVG file.
If you have the files stored on the server (I don't), you can simply set the href in the SVG.
In my case, I'll convert the files to base64 and embed them in the SVG.
Edit: The SVG worked very well. If you are only going to download the files, ZIP might be better. If you are going to display the files, then SVG seems superior.
When using Ajax components it is possible to start multiple downloads. Therefore you have to use https://cwiki.apache.org/confluence/display/WICKET/AJAX+update+and+file+download+in+one+blow
Add an instance of AJAXDownload to your Page or whatever. Create an AjaxButton and override onSubmit. Create an AbstractAjaxTimerBehavior and start downloading.
button = new AjaxButton("button2") {
private static final long serialVersionUID = 1L;
#Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form)
{
MultiSitePage.this.info(this);
target.add(form);
form.add(new AbstractAjaxTimerBehavior(Duration.milliseconds(1)) {
#Override
protected void onTimer(AjaxRequestTarget target) {
download.initiate(target);
}
});
}
Happy downloading!
Below code 100% working.
Step 1: Paste below code in index.html file
<!DOCTYPE html>
<html ng-app="ang">
<head>
<title>Angular Test</title>
<meta charset="utf-8" />
</head>
<body>
<div ng-controller="myController">
<button ng-click="files()">Download All</button>
</div>
<script src="angular.min.js"></script>
<script src="index.js"></script>
</body>
</html>
Step 2: Paste below code in index.js file
"use strict";
var x = angular.module('ang', []);
x.controller('myController', function ($scope, $http) {
var arr = [
{file:"http://localhost/angularProject/w3logo.jpg", fileName: "imageone"},
{file:"http://localhost/angularProject/cv.doc", fileName: "imagetwo"},
{file:"http://localhost/angularProject/91.png", fileName: "imagethree"}
];
$scope.files = function() {
angular.forEach(arr, function(val, key) {
$http.get(val.file)
.then(function onSuccess(response) {
console.log('res', response);
var link = document.createElement('a');
link.setAttribute('download', val.fileName);
link.setAttribute('href', val.file);
link.style.display = 'none';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
})
.catch(function onError(error) {
console.log('error', error);
})
})
};
});
NOTE : Make sure that all three files which are going to download will be placed in same folder along with angularProject/index.html or angularProject/index.js files.
Getting list of url with ajax call and then use jquery plugin to download multiple files parallel.
$.ajax({
type: "POST",
url: URL,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: data,
async: true,
cache: false,
beforeSend: function () {
blockUI("body");
},
complete: function () { unblockUI("body"); },
success: function (data) {
//here data --> contains list of urls with comma seperated
var listUrls= data.DownloadFilePaths.split(',');
listUrls.forEach(function (url) {
$.fileDownload(url);
});
return false;
},
error: function (result) {
$('#mdlNoDataExist').modal('show');
}
});
Here is the way I do that. I open multiple ZIP but also other kind of data (I export projet in PDF and at same time many ZIPs with document).
I just copy past part of my code.
The call from a button in a list:
$url_pdf = "pdf.php?id=7";
$url_zip1 = "zip.php?id=8";
$url_zip2 = "zip.php?id=9";
$btn_pdf = "<a href=\"javascript:;\" onClick=\"return open_multiple('','".$url_pdf.",".$url_zip1.",".$url_zip2."');\">\n";
$btn_pdf .= "<img src=\"../../../images/icones/pdf.png\" alt=\"Ver\">\n";
$btn_pdf .= "</a>\n"
So a basic call to a JS routine (Vanilla rules!).
here is the JS routine:
function open_multiple(base,url_publication)
{
// URL of pages to open are coma separated
tab_url = url_publication.split(",");
var nb = tab_url.length;
// Loop against URL
for (var x = 0; x < nb; x++)
{
window.open(tab_url[x]);
}
// Base is the dest of the caller page as
// sometimes I need it to refresh
if (base != "")
{
window.location.href = base;
}
}
The trick is to NOT give the direct link of the ZIP file but to send it to the browser. Like this:
$type_mime = "application/zip, application/x-compressed-zip";
$the_mime = "Content-type: ".$type_mime;
$tdoc_size = filesize ($the_zip_path);
$the_length = "Content-Length: " . $tdoc_size;
$tdoc_nom = "Pesquisa.zip";
$the_content_disposition = "Content-Disposition: attachment; filename=\"".$tdoc_nom."\"";
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header($the_mime);
header($the_length);
header($the_content_disposition);
// Clear the cache or some "sh..." will be added
ob_clean();
flush();
readfile($the_zip_path);
exit();
<p class="style1">
<a onclick="downloadAll(window.links)">Balance Sheet Year 2014-2015</a>
</p>
<script>
var links = [
'pdfs/IMG.pdf',
'pdfs/IMG_0001.pdf',
'pdfs/IMG_0002.pdf',
'pdfs/IMG_0003.pdf',
'pdfs/IMG_0004.pdf',
'pdfs/IMG_0005.pdf',
'pdfs/IMG_0006.pdf'
];
function downloadAll(urls) {
var link = document.createElement('a');
link.setAttribute('download','Balance Sheet Year 2014-2015');
link.style.display = 'none';
document.body.appendChild(link);
for (var i = 0; i < urls.length; i++) {
link.setAttribute('href', urls[i]);
link.click();
}
document.body.removeChild(link);
}
</script>

How to return value from a jsp page

I have a jsp page which has java scriplets, and which is displaying the required output using out.println(obj), but I want to return this 'obj' so that these values can be used in another js file. How to return this from the jsp page?
So the js file is:
(function() {
document.addEventListener('DOMContentLoaded', function() {
var gridDiv = document.querySelector('#myGrid');
var gridOptions = {
columnDefs: [
{headerName: 'CLIENT_ACRONYM', field: 'CLIENT_ACRONYM'},
{headerName: 'ORDER_QTY', field: 'ORDER_QTY'},
]
};
new agGrid.Grid(gridDiv, gridOptions);
jsonLoad( function(data) {
gridOptions.api.setRowData(data);
});
});
})();
function jsonLoad(callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', '../output.json'); // by default async
xhr.responseType = 'json'; // in which format you expect the response to be
xhr.onload = function() {
if(this.status == 200) {// onload called even on 404 etc so check the status
callback(this.response);
}
};
xhr.onerror = function() {
console.log('loading data error');
};
xhr.send();
}
JSP file returning Jsonarray:
JSONArray jsonArray = new JSONArray(orderDetailsList1);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(jsonArray);
So, instead of output.json in the js file I need to pass the JSOn Object returned by the jsp file. How to do that?
Use this code in jsp file
<input type="hidden" value="<%out.println(obj);%>" id="objValue"/>
In js file you can get the value by its id as
var objValue = document.getElementById("objValue");
Basically scriplets in jsp is not good.
Store in session scope or request scope and use it,like session.setAttribute('obj','value') in servlet and value="${obj}" in jsp.
Put that value in <div id=""> or <p id=""> tag which has ID in jsp and get that value in any js using getElementByID.

calling a Java method by AJAX

Actually I've been reading about this for a while but I couldn't understand it very well.
Here is a snippet of the Servlet "ProcessNurseApp" :
if (dbm.CheckExRegNumber(Candidate.getRegNumber()) == true) {
// Show him an alert and stop him from applying.
out.println("<script>\n"
+ " alert('You already Applied');\n"
+ "</script>");
out.println("<script>\n"
+ " window.history.go(-1);\n"
+ "</script>");
}
So when the form named "ApplicationForm" in the "Nurses.jsp" get submitted it goes to that method in servlet after some Javascript validation.
My issue is that I want to call that method
if (dbm.CheckExRegNumber(Candidate.getRegNumber()) == true)
in the JSP page without getting to servlet so I can update values without refreshing the page. I've been reading that using ajax with jQuery would be the best way to do that, so can anyone help me of calling the above if statement from jQuery by AJAX.
Try an ajax call to the servlet(not possible without calling servlet) to check whether the function returns true or false then return a flag according to the value(true or false). On that basis you can show an alert or anything else.
For ajax call, you can use:
$.post( "ajax/Servlet_Url", function( data ) { if(data==true) alert("You already Applied"); else window.history.go(-1);});
Refer to following Link for more details about jQuery post request.
https://api.jquery.com/jquery.post/
jQuery(document).ready(function($) {
$("#searchUserId").attr("placeholder", "Max 15 Chars");
$("#searchUserName").attr("placeholder", "Max 100 Chars");
$.ajax({
url:"../../jsp/user/userMaster.do",
data: { drpType : 'userType',lookType : "1" },
success: function (responseJson) {
var myvalue = document.getElementById("userTypeKey");
for(var val in responseJson)
{
valueType = val;
textOptions = responseJson[val];
var option = document.createElement("option");
option.setAttribute("value",valueType);
option.text = textOptions;
myvalue.add(option);
if(valueType == myvalue.value)
{
option.selected = "selected";
}
}
}
});
});

servlet not responding back to ajax request

servlet is not sending back response to ajax code. Plaease help!!!
html code, here output should be printed
this is ajax code in javascript
<script language="javascript">
reqObj=null;
function getPrice(){
if(window.XMLHttpRequest){
reqObj=new XMLHttpRequest();
}else {
reqObj=new ActiveXObject("Microsoft.XMLHTTP");
}
reqObj.onreadystatechange=process;
var area = document.getElementById('product').value;
var fType= document.getElementById('size').value;
reqObj.open("POST","./getPricefromSize?pro="+area+"&size="+fType,true);
reqObj.send(null);
}
function process1(){
if(reqObj.readyState==4){
var prce=reqObj.responseText;
document.getElementById("price").innerHTML=prce;
}
}
</script>
this is my servlet code:
String str=request.getParameter("pro");
String str1=request.getParameter("size");
PrintWriter out1=response.getWriter();
System.out.println("pro: "+str+"size: "+str1);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:linpaws","system","oracle");
st=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
rs=st.executeQuery("select price from labpro where usernm='"+labid+"' and product='"+str+"' and sze='"+str1+"'");
rs.first();
price=rs.getString(1);
System.out.println("price"+price);
out1.write(price);
rs.close();
st.close();
output is printed in console. But not showing in ajax call
You are missing some bits out of your code:
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");
http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp should put you on the right track.
Another reason its not working is your assigning process to your onreadystatechange e.g
onreadystatechange=process but process must exactly match the name of the function your assigning which in your case is process1 so the code would become reqObj.onreadystatechange=process1.

How to show value from database to jsp without refreshing the page using ajax

I am an Ajax fresher
Ajax
function ajaxFunction() {
if(xmlhttp) {
var txtname = document.getElementById("txtname");
xmlhttp.open("POST","Namelist",true);
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("txtname=" + txtname.value);
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
document.getElementById("message").innerHTML=xmlhttp.responseText;
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
jsp
<form name="fname" action="Namellist" method="post">
Select Category :
<select name="txtname" id="txtname">
<option value="Hindu">Hindu</option>
<option value="Muslim">Muslim</option>
<option value="Christian">Christian</option>
</select>
<input type="button" value="Show" id="sh" onclick="ajaxFunction();">
<div id="message">here i want to display name</div><div id="message1">here i want to display meaning</div>
</form>
servlet
String ct=null;
ct=request.getParameter("txtname");
Connection con=null;
ResultSet rs=null;
Statement st=null;
try{
con=Dbconnection.getConnection();
PreparedStatement ps=con.prepareStatement("select name meaning from (select * from namelist order by dbms_random.value)where rownum<=20 and category='+ct+'" );
rs=ps.executeQuery();
out.println("name" + rs);
**Here I have confusion,**
}
catch(Exception e)
{
System.out.println(e);
}
How can i diaplay servlet value to jsp.
Please help me? or please provide some good tutorial links.
You have to make below changes :-
In Servlet :-
Set the response content type as:- response.setContentType("text/xml"); in top section of the servlet. By setting this we can send the response in XML format and while retrieving it on JSP we will get it based on tag name of the XML.
Do whatever operation you want in servlet...
Save the value for ex-
String uname=";
uname="hello"; //some operation
//create one XML string
String sendThis="<?xml version='1.0'?>"
+"<Maintag>"
+"<Subtag>"
+"<unameVal>"+uname+"</unameVal>"
+"</Subtag>"
+"</Maintag>"
out.print(sendThis);
Now we'll go to JSP page where we've to display data.
function getXMLObject() //XML OBJECT
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
function ajaxFunction() {
if(xmlhttp) {
xmlhttp.open("GET","NameList",true); //NameList will be the servlet name
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(null);
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
getVal();
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
function getVal()
{
var xmlResp=xmlhttp.responseText;
try{
if(xmlResp.search("Maintag")>0 )
{
var x=xmlhttp.responseXML.documentElement.getElementsByTagName("Subtag");
var xx=x[0].getElementsByTagName("unameVal");
var recievedUname=xx[0].firstChild.nodeValue;
document.getElementById("message").innerText=recievedUname;//here
}
}catch(err2){
alert("Error in getting data"+err2);
}
}
And here you are done. :)
1.In servlet code
PrintWriter output = response.getWriter();
String result = "value";
writer.write(result);
writer.close()
2. Why you don't use jquery ?
You can replace your code on -
$.post('url', function(data) {
$('#message1').html(data);
});
query post example
Probably off the hook but might be useful, rather than putting up all the javascript for Ajax call use some javascript library preferably jQuery for making the Ajax call.
Any javascript library you use will help you make the code compact and concise and will also help you maintain cross browser compatibility.
If you planning to write all the XHTTP code yourself, you might end up spending a lot of time for fixing cross browser issues and your code will have a lots of hacks rather than the actual business logic.
Also, using library like jQuery will also achieve the same stuff with less number of lines of code.
Hope that helps.

Categories

Resources