I have a PHP script that produces a .CSV export file from a MySQL DB. The backend script formats the output and uses header()‘s to open the pop-up window in the browser to download the .CSV. — Tested and works fine.
I also have a web page that has a graphic button that launches an Ajax call to the server to produce the download .CSV file when you click the graphic button.
I tested the click event with a JavaScript alert() and it works fine.
I tested the click event with the Ajax call and nothing happens. Seems like I somehow need to direct the backend script to behave a bit differently.
Has anyone done anything similar to this before?
Thanks.
* HMTL (Excerpt) *
<div id="exportButton"><img src="images/export.png" alt="Export to Microsoft Excel Graphic" /></div>
<h2>Page Title</h2>
<br clear="all" />
<div id="pageContent_wrapper">...
* JavaScript *
<script>
jQuery.support.cors = true; // needed for ajax to work in certain older browsers and
versions
$(document).ready(function(){
$('#exportButton').click(function() {
//alert('button clicked');
$.ajax({
url: "http://mydomain.com/js/ajax/exportCSV.php"
});
});
}); // end .ready()
</script>
I am trying to accomplish this feature without having to send the user back to the server. I want the user to stay on the page.
You can’t do a download from an AJAX call. The easiest solution is to wrap the button in an
<a>element, and let the browser handle the download naturally. If you really need to have JS involved, change thedocument.locationto point to the download PHP instead of invoking AJAX.