File download from JSF with a rendered response - jsf-2

I have some dynamically generated files which I want my JSF 2.0 app to download for the user. I've been able to get this working using the code found in the solution here :
Forcing a save as dialogue from any web browser from JSF application
and a command button in a form on the page
And that works fine except for one hitch. I'd like to be able to render a message back to the user on the initial page that tells them their file is being processed and to please wait. Obviously the responseComplete call stops that from happening. Is there some way to re-render the submitting page and send back a file from the same button?

No, you can't. You can send only one response back per request. Best what you could do is to use JavaScript to show an initially hidden div or something which contains the message during the onclick. But you'll have the problem that you cannot hide it whenever the download is completed.
An alternative is to store the file on temp disk and return a fullworthy JSF response wherein you display a download link which returns the file from temp disk by a standalone servlet.

I think you can use ajax to solve this. Call the method that creates the file from an ajax action and provide a javascript callback to handle the navigation or to show a layer or whatever
<script type="text/javascript">
function processEvent(data) {
if (data.status == "begin") {
showWaitingLayer();
} else if (data.status == "success") {
hideWaitingLayer();
showDownloadLink();
}
}
</script>
<h:commandLink action="#{myBean.createDocument}">
<f:ajax onevent="processEvent"/>
</h:commandLink>

Related

jQuery Mobile Site using an ajax $.get() to check username availability returning previous page code in return data

I have a simple JQM site I'm working on. I'm trying to validate the availability of a username on the fly in a form. I'm using jquery $.get() ajax to return "success" or "fail" however the return data is being replace with the code of the previous page.
$(document).on('pageinit', function () {
// check to see if username is available
$("#username").change(function() {
$.get("controller.php", { action: "check_username", username: username }, function(data) {
console.log(data);
}
});
The controller.php is checking for availability of the username and return "pass" or "fail" When I do the console.log(data) which I'm expecting to be pass or fail, it's logging out the code from the previous page??
I'm thinking maybe it's a JQM caching issue so I tried to disable cache with no effect. I was orginally using a JQM dialog box to display the form. Thinking that had something to do with it I pulled that out and loaded a straight link. That didn't fix it so I tried to load the page directly using
$.mobile.changePage( "user-new.php", { reloadPage: true});
I am stumped. Why would a $.get ajax call return data be returning code from the previous page?
Here's a face palm! My controller was authenticating and kicking it back out to a login page. Apparently php redirects act funky with ajax return data. Rather then returning the login page code it was returning the previous page code. I Removed the authentication and it works fine. Unbelievable! I'm going to go work at a gas station or something :)

Grails file download does not initiate when called from remoteFunction

In my Grails application, a user can click on a g:link which will call my controller to export certain data to a CSV file. This works with no problems.
I then moved that button to a jQuery dialog box and, when the button is clicked, I use
${remoteFunction(action:'export', onSuccess:'closeMe();', id:courseInstance?.id)}
to call the same controller method and close the dialog box. I've confirmed that the method is actually called, and the dialog box closes. The user is not prompted with the CSV dowmload, however. I'm assuming this has something to do with the remoteFunction, but I'm not really sure. Can anyone explain why this might happen, and a potential fix?
Thanks!
With AJAX requests you can't handle to download content as attachment and so it can't trigger the Save As dialog.
There are a couple of workarounds for this:
Use a plain g:link as before and bind the 'closeMe();' function to the 'click' event. The problem is that you have no control on error or success response.
Use an iframe: You can create a temporary invisible iframe and set its location to the URL of the file to download. It also has the backside of not controlling the success/error response.
The code could be the same as in this answer:
<script type="text/javascript">
function downloadURL(url) {
var iframe;
var hiddenIFrameID = 'hiddenDownloader';
iframe = document.getElementById(hiddenIFrameID);
if (iframe === null) {
iframe = document.createElement('iframe');
iframe.id = hiddenIFrameID;
iframe.style.display = 'none';
document.body.appendChild(iframe);
}
iframe.src = url;
}
</script>
And the link
Export

How to load the page as popup dialog without specifying "data-rel" in the caller link

Hi i'm new to Jquery mobile,have some servlet which evaluates username and password from login.html page as,
if(un.equals("user1") && pd.equals("password1")){
RequestDispatcher rd=request.getRequestDispatcher("welcome.html");
rd.forward(request, response);}
else {
RequestDispatcher rd=request.getRequestDispatcher("loginfailed.html");
rd.forward(request, response);}
}
i
what i'm trying is when login fails loginfailed.html should open as a popup dialog showing login failure notice example here. Pls help me to do this..
I've been using this:
http://dev.jtsage.com/jQM-SimpleDialog/
Much easier to open from within javascript than the default jquery-mobile dialog, plus it looks like a dialog in that it does not take up the whole page.

File upload struts 2 with Ajax

I am uploading a file using struts 2 with jsp as front end, but I dont want to refresh the page after the file is uploaded, so i am using Ajax but with that I am not able to get the File object in action, it seems file upload needs form tag in jsp,and if I am submitting the form then the page gets refreshed.
I researched through the net but cant get many relevant results, it would be of great help if someone guides me through this, is there a way for it. Any help would really be appreciated.
Best regards
I suggest to use iframe for upload file instead of ajax,
Sample code for Upload Csv file using struts2 and iframe :
var file = $("#fileUpload").val();
if(file.indexOf(".") != -1 && file.substr(file.indexOf("."))==".csv"){
/* created IFrame For UPload file*/
var iframe = $('<iframe name="uploadIPAddressIFrame" id="uploadIPAddressIFrame" style="display: none" />');
$("body").append(iframe);
/* Set Form for submit iframe*/
var form = $('#ipPoolForm');
form.attr("action", "uploadCSVFile.do");
form.attr("target", "uploadIPAddressIFrame");
form.submit();
openDialog(title);
/* handle response of iframe */
$("#uploadIPAddressIFrame").load(function () {
response = $("#uploadIPAddressIFrame")[0].contentWindow.document.body.innerHTML;
$("#chkIPAddressDiv").html(response);
$("iframe#uploadIPAddressIFrame").remove();
});
After upload if you submit form then change target of form :
// Because of using iframe for upload set target value
$("#ipPoolForm").attr("target", "");

Can you pick a browser target server-side?

I have a form that lets users select checks, and when submitted, creates a PDF, which opens in a new browser tab. It doesn't have any branding, and will probably open in a plugin anyway, so I don't want it taking over my site's tab. So I set the form's target to _blank.
But it's possible for the user to submit the form without enough information to create the PDF, in which case I flag the error (server-side) and re-render the form. But because I set the form's target, this re-render opens in a new tab as well, and that's not what I want - in this case, I want it to behave as if target were _top.
So the question is: Can I change the browser's rendering target server-side?
Yes, I know that this can be done with client-side JavaScript, but JS annoys me, and I have to do the validation server-side anyway. I may end up having to use it, but please don't suggest it as an answer - I'm more curious if what I'm attempting can even be done.
PS: I'm on Ruby on Rails 2.3.8, in case anyone knows a framework-specific solution.
A workaround on this problem would be to use the content-disposition header on the pdf, in order to force the file to be downloaded, and avoid the whole "target" approach..
Content-type: application/pdf
Content-Disposition: attachment; filename="downloaded.pdf"
No. This is a purely client-specific feature. As a matter of fact, it's quite possible to get a browser that supports only one window and where the target attribute would have simply no effect. There were even efforts to make this attribute disappear from future HTML standards completely (for instance, the XHTML branch had no such attribute).
The only overlap that I can think of between HTML and HTTP are the <meta http-equiv> tags (where HTML can affect otherwise HTTP-controlled behavior). HTTP is a transfer protocol, designed to work with about just any kind of data. Letting it control presentation would be a pretty terrible mix of concerns.
Fortunately, we live in a JavaScript-enabled world. It is rather easy to validate a form using an AJAX request, especially with libraries like jQuery.
For instance, this script performs a POST request to an URL (in this case, /pdf/validate) and expects the page to send back "ok" (if everything's good) or something else if there was an error.
<form method="post" action="/pdf/send" id="pdf-form">
<!-- form stuff here -->
</form>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
// set to true if we are to bypass the check
// this will happen once we've confirmed the parameters are okay
var programmaticSubmit = false;
// attach an event handler for when the form is submitted
// this allows us to perform our own checks beforehand; we'll do so by
// cancelling the event the user triggered, and do the submit ourselves if
// we detect no error
$('#pdf-form').submit(function(event)
{
if (!programmaticSubmit)
{
// first off, cancel the event
event.preventDefault();
// do an AJAX request to /pdf/validate
$.ajax("/pdf/validate", {
type: "POST",
data: $(this).serialize(), // send the form data as POST data
success: function(result)
{
// this gets called if the HTTP request did not end
// abnormally (i.e. no 4xx or 5xx status);
// you may also want to specify an "error" function to
// handle such cases
if (result == "ok")
{
// since the server says the data is okay, we trigger
// the event again by ourselves, but bypassing the
// checks this time
programmaticSubmit = true;
$(this).submit();
}
else // something went wrong! somehow display the error
alert(result);
}
});
}
});
});
</script>

Resources