Forcing "Save As" dialog via jQuery GET

Scott B picture Scott B · Jul 14, 2011 · Viewed 12.3k times · Source

I'm calling a jQuery "GET" on the test.php file code below.

I'm trying to get the script to pop a "Save As" dialog on the resulting test.ini file to allow it to be saved locally. However, although I can echo the result back to the jQuery fine, I can't seem to pop the "save as" dialog.

Update: Thanks to the solutions below, I just changed my $.get to a window.location.replace.

$('#test').click(
    function()
    {
        //$.get('<?php echo get_bloginfo('template_directory') ?>/test.php');
        window.location.replace("<?php echo get_bloginfo('template_directory') ?>/test.php");

    }
);

Answer

Jimmy Baker picture Jimmy Baker · Jul 14, 2011

You can't get an ajax request to show a "Save As" dialog, but what you CAN do is insert a hidden iframe element in the page, then set the source of that iframe to the url you want the user to download. Voila, there's your Save As.

Here's a copy and paste example:

$('a#linky').click(function(){
  var iframe = document.createElement("iframe"); 
  iframe.src = 'http://example.com/branding.zip'; 
  iframe.style.display = "none"; 
  document.body.appendChild(iframe);
  return false;
});