Downloading a file from PHP (or anything else) directly from a jQuery POST

Problem:

You have a file that is dynamically generated by some server side code that is triggered by a POST request but you just want the file to download and not force the user to leave the page that they are on.  Because that is how it “should” work.  Typically though you insert some form into the page and they are directed off of the page to download the file.

Solution:

By leveraging jQuery, we can perform several actions.  When the “export” button (in this example a div with the id “export search”) is clicked the following jQuery code is run. The first thing we need to do is dynamically append a form to the page where the button was clicked.  In our form we need to have the page where the file is going to be downloaded from and a hidden input type with our POST variable and value.  Once the form has been appended to the page, we want to submit it and them remove the form since we no longer need it.  After the form is submitted the file will automatically start downloading.

$(document).on('click',"#export_search", function() {
 var search_val=$("#search_input").val();
 $('<form action="./php/export.php" method="post"><input type="hidden" name="search_term" value='+search_val+'></form>').appendTo('body').submit().remove();

});