2

Right now, I have a webapp that uses the jquery ajax to make a call (with params that change from call to call via a form) to my backend and retrieve an xml file. I want to put the xml data into a file with a different extension for a private application.

Basically I just want the user to be able to click a button, and it automatically prompts them to "open or save" a file containing the returned ajax xml data.

I've dabbled with sending a raw http header using php, but I can't figure out how to get it to work. I'm writing all of this in javascript and jquery.

The only thing the below code does is (1)Make the Ajax Call, (2)Write the XML into an HTML page, (3) open the HTML page.

var format = function() {   
  $("button#format").click(function() {
    $("#form").submit();
    $.ajax({
      url: "find",
      beforeSend: function (xml) {
        xml.overrideMimeType("application/octet-stream; charset=x-user-defined");
      },
      data: $("form#form").serialize(),
      dataType: "html",
      success: function(xml) {
        xmlWindow = window.open("download.ivml");
        xmlWindow.document.write(xml);
        xmlWindow.focus();
      },
      error: function(request) {
        $("#webdiv").html(request.responseText);
      }
    });
  });
};
lmcanavals
  • 2,339
  • 1
  • 24
  • 35
somegirl88
  • 21
  • 1
  • duplicate: http://stackoverflow.com/questions/365777/starting-file-download-with-javascript – dragon Mar 13 '12 at 21:26

1 Answers1

0

There is no need to force something like this into the AJAX paradigm, unless you need to play around with the data you retrieve before making it available for the user, then again, that should be able to be done in php. So I would do something like this:

<form id="format" action="download.ivml" target="_blank">
...
</form>

And in jquery modify the action like this

​$('#format')​.submit(function(){
    // tweaking the post data, otherwise this whole block is not needed.
    return true;    
})​;

Finally on my server use a .htaccess file to handle that weird URL download.ivml

Options +FollowSymLinks
RewriteEngine on
RewriteRule ^(.*)download.ivml$  /path/to/where/I/process/the/request

not quite sure about the syntaxis of this last .htaccess file though.

lmcanavals
  • 2,339
  • 1
  • 24
  • 35
  • Edited the jquery portion, because it was redundant. That jquery block is not necessary if there is no tweaking of the data before submitting the form. – lmcanavals Mar 13 '12 at 23:50