0

I need to write a String in a file on the client side, however as the Internet protocol does not allow that for Security concerns, this is the workaround I did: I have an AJAX request which invokes a JSP that queries a Database to get a String. I need to show the users a "Save-As" dialog and write this String to the local path they specify.

My JavaScript function:

function openReport(id)
{
    var url = "../reports/reportsHandler.jsp?id=" + id;

    var xmlhttp;
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            //alert(xmlhttp.responseText);
            alert("result obtained");
        }
    }
    xmlhttp.open("POST", url, true);
    xmlhttp.send();
}

In the JSP, I have something like this:

response.setHeader("Content-Disposition", "attachment;filename=report.xml");
out.println(stringObtainedFromDatabase);

I do not see a Save As dialog while I get the alert saying result obtained. This is the first time I am doing this, could you please tell me if I am doing something wrong?

But, is there a way in JavaScript to show users a Save-As dialog and write the content of "div" tag in a file on the Client system?

Shankar Raju
  • 4,356
  • 6
  • 33
  • 52

1 Answers1

2

Use a regular HTTP request, not an AJAX (XMLHttpRequest) one.

function openReport(id)
{
    var url = "../reports/reportsHandler.jsp?id=" + id;
    window.location = url;
}

This will send an HTTP GET, not a POST, though it looks like GET is the correct HTTP method to use here anyway, since you're retrieving data and not actually altering anything on the server.

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • Awesome, that worked! However why doesn't an AJAX request work for content-disposition? – Shankar Raju May 11 '12 at 14:59
  • Because you can't use AJAX to download files to disk, ever. See http://stackoverflow.com/questions/3502267/download-a-file-using-ajax and http://stackoverflow.com/questions/676348/allow-user-to-download-file-using-ajax – Matt Ball May 11 '12 at 15:11