How to export javascript ajax data to csv? [duplicate] - javascript

This question already has answers here:
Download file through an ajax call php
(6 answers)
Closed 8 years ago.
What I want to do:
1,use Javascript ajax POST array to PHP;
2,use POST array to search result from mysql with PHP;
3,return search results with csv format, so user can save the file.
I have accomplished part 1 and part 2, but I can't get csv file returned
I use ajax to POST array data to PHP like this:
$(document).ready(function(){
$('#export').click(function(){
var list = JSON.stringify(count);
$.ajax({
type: "POST",
url: "exportDataColoniesNumber.php",
data: {'data': list},
success: function(response){
alert(response);
}
});
});
});
And process the data in exportDataColoniesNumber.php, and the page is to return a csv file:
<?php
$data = json_decode($_POST['data']);
$last_key = end(array_keys($data));
$sql = "SELECT * FROM coloniesNumber WHERE ";
foreach ($data as $key => $value) {
$sql .= "num='" . $value . ($key == $last_key ? "';" : "' OR ");
}
$con = DatabaseConnection::get()->connect();
mysql_query('set names utf8');
mysql_select_db('fish') or die('Could not select database');
$result = mysql_query($sql);
$lines = '';
while($row = mysql_fetch_array($result)) {
$line = '';
for($i = 0; $i < $fields; $i++) {
$line .= $row[$i] . ",";
}
$lines .= trim($line) . "\n";
}
header("Content-type:application/vnd.ms-excel");
header("Content-disposition:csv".date("Y-m-d").".csv");
header("Content-disposition:filename=test.csv");
print "$lines";
?>
The alert(response) return csv data:
8,4008,11.267,fat,1,,
9,4009,12.022,thin,1,,
10,4010,11.356,thin,1,,
11,4011,10.873,thin,1,,
12,4012,11.017,thin,1,,
13,4013,11.301,thin,1,,
How can I get csv file returned ?

Personally i've created a PHP handler that exports to csv, make sure you have these headers
header("Content-Disposition: attachment; filename=report.csv");
header("Content-Type: text/csv");
Then just echo your data, csv-formatted or use one of the many free csv classes that does that for you (just call a function with an Array as a parameter)
Then make your form (asuming you have one) post to a hidden iframe of 1x1 pixels and set offscreen with css
iframe { position: absolute; left: -9999px; }
You should be all set, and the export will pop up - however, make sure the file is not big or your script takes a lot of time to complete - until then, the download won't show up.

Related

AJAX code not working in relation to JSON and PHP when retrieving data from database

I am creating a search. The user searches for a city and the top 10 attractions for that city appear in divs. I want one attraction per div, before I tried to add any JSON the data was all appearing in one div.
Within my AJAX code, I am getting the alert meaning there is some sort of error, but I am not sure what. This is my AJAX code
$.ajax({
url: 'searching.php',
type: 'POST',
dataType: 'json',
success: function(data){
$('#return').html(data.html);
},
error: function(jqXHR, textStatus, errorThrown){
$('#return').html('');
alert('Error Loading');
}
});
Within the searching.php is where I connect to the database and where I retrieve the data from. Within an if statement, if there is a result in the database matching the one that was entered into the search bar then return this information.
else {
while ($row = mysqli_fetch_array($result)) {
$attraction_name = $row['attraction_name'];
$image = "<img src='{$row['image']}' height='100' width='100'>";
$lat = $row['lat'];
$long = $row['long'];
$cost = $row['cost'];
$output .= "<li>$attraction_name $lat $long $cost $img</li>";
}
$json = array();
$json['html'] = '<li>' . $output . '</li>';
header('Content-Type: application/json');
echo json_encode( $json );
}
Within the HTML there is a div id = #return. I would like to place the attraction name, the image of the attraction, where it is on the map and the cost of the attraction within a div. But each div needs to be different as there is 10 different attractions. Ultimately I would love to know how to add separate divs to match a certain row of data in MySQL. However, if I could figure out why there is an error in my AJAX, that would be great.
<?php
$json = array('hmtl' => '<li>' . $output . '</li>');
echo json_encode( $json );
?>
Have you tried like this to define your array ?
If i 'm right your project will display a different answer in different div in function of an id ? imo To solve that you need to create a loop in your ph file to return a complete array with all your information.
$image = "<img src='{$row['image']}' height='100' width='100'>";
$lat = $row['lat'];
$long = $row['long'];
$cost = $row['cost'];
$output .= "<li>$attraction_name $lat $long $cost $img</li>";
have you seen the $img and $image ?

PHP array to seperate JavaScript file via AJAX

I made a simple php file, that saves data from MySQL db into 2 arrays. I am trying to send these two arrays to the js file (which is on seperate from the html file). I am trying to learn AJAX, but it seems i am not doing something correct.
Can you please explain what am i doing wrong?
My php file: get.php
<?php
define('DB_NAME', 'mouse');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_HOST', 'localhost');
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}else{
echo 'Successfuly connected to database :) <br/>';
}
$sql = "SELECT x, y FROM mousetest";
$result = mysqli_query($link, $sql);
$x_array = [];
$y_array = [];
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "x: " . $row["x"]. " - y: " . $row["y"]. "<br>";
array_push($x_array, $row["x"]);
array_push($y_array, $row["y"]);
}
} else {
echo "0 results";
}
echo json_encode($x_array);
echo "<br>";
echo json_encode($y_array);
mysqli_close($link);
$cd_answer = json_encode($x_array);
echo ($cd_answer);
?>
And this is my JS file:
$(document).ready(function(){
$.ajax({
type: "GET",
url: "get.php",
dataType: "json",
data : {anything : 1},
success:function(data){
var x = jQuery.parseJSON(data); // parse the answer
x = eval(x);
console.log(x.length);
}
});
});
I really hope you understand, what i am trying to do. Where is the problem? I really thought this should work, as i went through it quite a few times to say the least...
You can't use echo json_encode(...) twice. The client expects a single JSON object, not a series of them.
You should make each array an element of a containing array, which you then return as JSON.
$result = array('x' => $x_array, 'y' => $y_array);
echo json_encode($result);
Then in the jQuery code you would use:
var x = data.x;
var y = data.y;
Also, when you use dataType: 'json', jQuery automatically parses the JSON when it sets data. You shouldn't call jQuery.parseJSON() or eval().

How to callback several variables from a page using jquery AJAX

I have spent hours(maybe days) on this problem. I know this question has been asked before but the answers are always so vague for my beginner experience level to understand. I would love some specific and simplified code exampes.
I am submitting an AJAX call to changeDate.php.
index.html
$(document).on("click", "#day-left", function(event){
changeDate = changeDate - 1;
$.ajax({
type: "POST",
url: "changeDate.php",
data: {
amount: changeDate,
loginName: "benjamin_lawson"
},
success: function(data) {
$("#date").html(data);
}
});
});
This page receives the ajax. Using the data it updates SQL and creates 24 variables ($hour1, $hour2, $hour3...) with data.
changeDate.php
<?php
$amount = $_POST['amount'];
$user = $_POST['loginName'];
//server information variables
$dateName = date("mdY", strtotime("+" . $amount . " day"));
$conn = new mysqli($servername, $username, $password, $dbname);
for ($x = 1; $x <= 24; $x++) {
$sql = "SELECT `$dateName` FROM `$user` WHERE hour='$x'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
${"hour" . $x} = $row[$dateName];
}
}
}
//this creates 24 variables with all my information I want sent
//through my call back. ($hour1, $hour2, $hour3,...)
How can I pass these variables back to my first page in a callback that keeps the variable name and variable data?
I see a related question to this and they answered with:
RELATED QUESTION AND ANSWER... potential solution
You can return arbitrarily many variables with json_encode().
Try in your PHP:
<?php
echo json_encode(array($num1, $num2));
?>
You can add to that array , $num3, $num4, ... and so on.
In your JS, you can access each number as follows.
First, you will need this line of code to parse the encoded JSON string, in > > your success function.
var result = $.parseJSON(output);
That sets result as a JSON object. Now you can access all fields within > result:
result[0] -- $num1 in PHP
result[1] -- $num2 in PHP
I would really appreciate if someone can show me in code what I need to do to make this work. Thank you so much!
Well every answer is telling to use JSON encode of php. And you required another answers, though theres is already existing a question on that.
Well from php, you can return any data you want. Either you can give a string, or directly HTML or some formatted data like xml or JSON.
Whatever echoed/printed from that request is a response. You can do that request directly from URL or by AJAX. If the request meets the prerequisites, it will show same response.
Now if you just echo any data, there JS no structure and probably you would have to format and parse it to extract meaningful data from it.
But JSON and XML are the know data transport languages. XML is good but needs structuring at server and element based retrieval at client side (there can be many efficient ways which I am unknown to; as I am not a fan of XML). For JSON, you have encode and decode methods at server end and JavaScript is like elder brother to it.
Now how do you form a JSON? You just pass array or object to json_encode and it will return the JSON string. echo that string and your response is ready.
So for I am going to use #Poonam's code; I am making few optimizations also:
$amount = $_POST['amount'];
$user = $_POST['loginName'];
//server information variables
$dateName = date("mdY", strtotime("+" . $amount . " day"));
$conn = new mysqli($servername, $username, $password, $dbname);
for ($x = 1; $x <= 24; $x++) {
}
// fill an array from 1 to 24 with steps of 1
// http://php.net/manual/en/function.range.php
$x = range(1, 24, 1);
$sql = "SELECT `$dateName`, hour FROM `$user` WHERE hour IN ('". implode( "', '", $x ) ."')";
$result = $conn->query($sql);
$response_arr = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response_arr['hour' . $row->hour] = $row[$dateName];
}
}
echo json_encode($response_arr);
exit(0);
//this creates 24 variables with all my information I want sent
And in the success callback of AJAX, use either JSON.parse() if content type is not mentioned as application/json.
here i use json to encode data .
$.ajax({
type:"POST",
async: false,
url:"finance/getdataq",
dataType: "json",
data: data,
success: function(data){
// you can access your data variables like data['ukeydt'];
$("."+targetval).find('.qrwordfol').html(data['ukeydt']);
$("."+targetval).find('img').attr('src',data['ukeyqr']);
$("."+targetval).show();
return false;
},
error: function (data) {
getd="";
}
});
and in my php code
public function getdataq()
{
$data = array();
$data['ukeydt'] = "this is first";
$data['ukeyqr'] = "this is second";
echo json_encode($data);
exit();
}
You can use an array which will have all values for hours.
In changeDate.php
$amount = $_POST['amount'];
$user = $_POST['loginName'];
//server information variables
$dateName = date("mdY", strtotime("+" . $amount . " day"));
$conn = new mysqli($servername, $username, $password, $dbname);
for ($x = 1; $x <= 24; $x++) {
$sql = "SELECT `$dateName` FROM `$user` WHERE hour='$x'";
$result = $conn->query($sql);
$response_arr = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response_arr['hour' . $x] = $row[$dateName];
}
}
}
echo json_encode($response_arr);
exit();
//this creates 24 variables with all my information I want sent
//through my call back. ($hour1, $hour2, $hour3,...)
This $response_arr will have $response_arr['hour1']...$response_arr['hour24'] and you can use this array in your success: function(data)
success: function(data) {
console.log(data);
}
You'll get your whole data in data

d3.js How to pass parameter to php for query condition

I attempt to combine d3, mysql php Tutorial.
I want to use mysql to store data, and use d3 table to display the result.
Following the tutorial I successfully connected the sql, and display it.
However, in my example, the where condition of sql in queryData.php is hard encoded.
As show below: WHERE pathwayID='1643685' && symbol='VIF'
I need to pass the parameter '1643685' and 'VIF' from d3 file to php file, how should I do?
And how should I modify queryData.php, thanks.
d3 file
d3.json("queryData.php", function(error, jsonData) {
....
});
queryData.php
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
// load in mysql server configuration (connection string, user/pw, etc)
include 'mysqlConfig.php';
// connect to the database
#mysql_select_db($database) or die( "Unable to select database");
//Query
$myquery = "
SELECT `pathwayID`, `proteinID`, `uniprotID`, `symbol`, `displaySymbol`, `reactomeID`, `cellularLocation` FROM `protein` WHERE pathwayID='1643685' && symbol='VIF'
";
$result = mysql_query($myquery);
if ( ! $result ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($result); $x++) {
$data[] = mysql_fetch_assoc($result);
}
echo json_encode($data);
mysql_close();
?>
mysqlConfig.php
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
$username="root"; //replace with your mySql username
$password=""; //replace with your mySql password
$database="pathway"; //replace with your mySql database name
$host="localhost"; //replace with the name of the machine your mySql runs on
$connection=mysql_connect($host,$username,$password);
?>
Finally, I solved this by using ajax to post parameter.
$.ajax({
url: "./php/querybyPathwayId.php",
type: "GET",
data: {
pathwaydbId: dbId
},
dataType: "json",
success: function (jsonData) {
operation(jsonData);
},
error: function () {
}
});
and modified the querycentance
$pathwayId = $_GET["pathwaydbId"];
$myquery = "
SELECT `pathwayID`, `proteinID`, `uniprotID`, `symbol`, `displaySymbol`,
`reactomeID`, `cellularLocation` FROM `protein` WHERE pathwayID='$pathwayId'
";

PHP populate drop box with jquery

I have a script which fetches options from a script php to populate a drop down list on the main page.
Here's the javascript
<script>
//# this script uses jquery and ajax it is used to set the values in
$(document).ready(function(){
//# the time field whenever a day is selected.
$("#day").change(function() {
var day=$("#day").val();
var doctor=$("#doctor").val();
$.ajax({
type:"post",
url:"time.php",
data:"day="+day+"&doctor="+doctor,
dataType : 'json'
success: function(data) {
//# $("#time").html(data);
var option = '';
$.each(data.d, function(index, value) {
option += '<option>' + value.timing + '</option>';
});
$('#timing').html(option);
}
});
});
});
</script>
Here's the php script which gets data from a database.
<?php
$con = mysqli_connect("localhost","clinic","myclinic","myclinic");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$doctor = $_POST['doctor'];
$day = $_POST['day'];
$query = "SELECT * FROM schedule WHERE doctor='" .$doctor."'AND day='" .$day. "'";
$result = mysqli_query($con, $query);
//$res = array();
echo "<select name='timing' id='timing'>";
//Initialize the variable which passes over the array key values
$i = 0;
//Fetches an associative array of the row
$row = mysqli_fetch_assoc($result);
// Fetches an array of keys for the row.
$index = array_keys($row);
while($row[$index[$i]] != NULL)
{
if($row[$index[$i]] == 1) {
//array_push($res, $index[$i]);
json_encode($index[$i]);
echo "<option value='" . $index[$i]."'>" . $index[$i] . "</option>";
}
$i++;
}
echo json_encode($res);
echo "</select>";
?>
It's not working. I get an error from console saying missing '}' in javasrcipt on line
$("#day").change(function(){
I can't seem to find an error either.
You need to add a comma on the line above the one triggering the error :
dataType : 'json',
It's because you don't have a comma on the line above it...
It's hard to say where is problem, because you mixed things together. On Javascript side you expect JSON but on PHP side you generate HTML.
Use JSON for sending data between server and browser. Ensure that you actually generate valid JSON and only JSON.
This line does nothing (function returns value, but not modifies it)
json_encode($index[$i]);
This line does not make sense - variable $res is not initialized;
echo json_encode($res);

Categories