开发者

jquery php and csv exporting

开发者 https://www.devze.com 2022-12-22 11:17 出处:网络
I have a script for exporting results of a mysql query as a csv file. The thing is that i use jquery to access the script. I need to know how i can return the data (already in csv format) with jquery.

I have a script for exporting results of a mysql query as a csv file. The thing is that i use jquery to access the script. I need to know how i can return the data (already in csv format) with jquery. In other words, just to make myself clear because my english is a bit poor, when the user presses a button in the html file, a post request is sent to a php file which returns the data in csv format. I want to take that data with jquery and serve the .csv file to the user.

PHP file:

<?php
    session_start();
    heade开发者_Go百科r ("Content-type: application/csv\nContent-Disposition: \"inline; filename=my.csv\"");
    include("config.php");
    $query = $_SESSION['sqlQuery'];

    $result = mysql_query($query) or die("Query failed : " . mysql_error());
    echo "ID,STATUS,CATEGORY,TITLE,DATE,URL\r\n"; //header
    while($row = mysql_fetch_row($result)) {
        echo "$row[0],$row[4],$row[3],$row[1],$row[2]\r\n"; //data
    }
?>

I need something in the HTML like:

$("#exportToCsv").click(function(){
   $.post("export.php",function(data){
        here the code for exporting much like downloading a file
  });
});


You can just link to the file (no ajax, no $.post) with the header henchman said. It will download the file. Ajax is ment for javascript to get the file, not to perfom download.


for which part of this task do you need help?

The following command prints a file to the user:

http://php.net/manual/en/function.file-get-contents.php

eg:

echo file_get_contents("myfile.csv");

edit

Try to add the following headers to your php-page, which will be called for your ajax call:

header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=\"export.csv\"");
0

精彩评论

暂无评论...
验证码 换一张
取 消