FuegoFingers
FuegoFingers

Reputation: 2199

Executing PHP script on Dojo Button click

I'm pretty sure I am over thinking this but I just cant figure it out. I have a dojo Button object that I want to execute a .php file when it is clicked. The php script runs a query and constructs a .xls file from it that it then prompts the user to download or open.

When I click the button I get the "loaded xhrGet" log but the prompt never appears so I don't believe the script is actually running.

           <button  data-dojo-type="dijit.form.Button" id="export_xls_button">Export to .xls
                <script type="dojo/method" data-dojo-event="onClick" >
                    dojo.xhrGet({
                        url: 'subRoutines/exportXLS.php',
                        load: function(response){
                            console.debug("loaded xhrGet");
                        },
                        error: function(error){
                            console.debug("error loading xhrGet");
                        }
                    });
                </script>
            </button>

Thank you for any help or suggestions.

Edit: The script does run just fine when I go directly to it in the web browser and php is turned on on the server.

Upvotes: 0

Views: 594

Answers (1)

laupow
laupow

Reputation: 128

You don't need to use XHRs for exporting a file. You can use click a standard link (or dojo button) which, when clicked, executes subRoutines/exportXLS.php. When the link is clicked, the script builds the file like normal and sends the file and appropriate http headers back to the user without leaving the page. No new location headers were sent to the browser, just a file.

This is a simple approach I use to export a a CSV file in PHP (you might only need the headers):

$fh = fopen("php://output", 'w');
fputcsv($fh, $csv_headers_array, ",", '"');
foreach ($csv_content_array as $line) {
    fputcsv($fh, $line, ",", '"');
}
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=filename.csv");
fclose($fh);
exit; 

And your dojo button becomes something like:

<button data-dojo-type="dijit.form.Button" id="export_xls_button">
    Export to .xls
    <script type="dojo/method" data-dojo-event="onClick" >
        window.location = 'subRoutines/exportXLS.php';
    </script>
</button>

Upvotes: 3

Related Questions