3

I'm trying to implement a tool to export data from a research website as a csv file. In my download controller, I have:

public function export(){
    $data = array(
          array('Name', 'Age', 'City'),
          array('Philippe', '23', 'Palo Alto'),
          array('John', '30', 'San Francisco'),
          array('Paul', '20', 'Los Angeles')
    );

    header('Content-type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=data.csv');

    $fp = fopen('php://output', 'w');
    foreach( $data as $line ) {
        fputcsv( $fp, $line );
    }
    fclose($fp);
}

and from my view, I do:

function download() {
     $('#download').empty().html('<img src="<?php echo base_url();?>/images/loader.gif" />');
     $.post('<?php echo base_url();?>/index.php/download/export');
}

and download() is fired up when the user click to a button with a onclick='download()'. However, I'm not seen the file being downloaded, nor a error message. When I look into my firebug console, I see:

200 OK 29ms jquery.min.js (line 4) HeadersPostResponseCookies

Name,Age,City Philippe,23,"Palo Alto" John,30,"San Francisco" Paul,20,"Los Angeles"

What am I missing? Thanks

1 Answer 1

3

You don't actually want an AJAX request here. You want to redirect your user to the file with:

window.location = '<?php echo base_url();?>/index.php/download/export';

The AJAX request is telling the server to send the data back to the script's success method. Since it's a download, the redirect won't make you leave the page so you can use this method without confusing your user.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.