New at Leaflet New at Leaflet - 4 years ago 155
Ajax Question

How to export data from database into Excel using AJAX call & JavaScript?

I have

containing some Farmers Ids,i want to to get the details (phone number, address, etc) from the database and export it to Excel file, I thought of using AJAX call to get the data from the database, but how can I export these data to Excel file?

JavaScript code:

function ExportData()
var ul = document.getElementById("FarmersID");
var items = ul.getElementsByTagName("option");
var farmers=[];

if (items.length == 0)
alert ("No Farmers Found!");
return false;
for (var i = 0; i < items.length; ++i)
var jsonString = JSON.stringify(farmers);

success: function (response)
error: function(jqXHR, textStatus, errorThrown) {
console.log('ERROR', textStatus, errorThrown);

PHP code:

include_once "connect.php";

$ids = join("','",$FarmerData);

$stmt ="SELECT * FROM Farmers where Farm_id IN ('$ids')";

foreach ($conn->query($stmt) as $row)
echo $row['nick_name_']."<br>";

Answer Source

You could use table2excel jquery plugin.

In your PHP code, just echo the database data that you execute in a simple HTML table.

After that in your jquery, append the response table from the php to your page, and use the table2excel plugin to export it:

success: function (response) 

      exclude: ".excludeThisClass",
      name: "Worksheet Name",
      filename: "SomeFile" //do not include extension
      fileext: ".xls", // MUST use .xls extension, only this will work

This is my example code in jsfiddle that I create:

Note, in this fiddle I'm using old version of table2excel, so it will download the file in .xlxs, which is unfortunately cannot be opened (known issue), so just rename it to .xls. But if you use the latest version, on the github link that I give you, it should work fine.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download