0

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();
    header ("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
  });
});

2 Answers 2

1

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.

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

Comments

0

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\"");

1 Comment

<?php session_start(); header ("Content-type: application/csv\nContent-Disposition: \"inline; filename=yourfilename.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 } ?> this is the php. So i need something in the html file like: $.post("exportCsv.php",function(data){ something here to export as a csv file (like to download the .csv file) });

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.