Sending data to PHP page to make a spreadsheet out of it - javascript

For some reason, when I try to send JSON data to a PHP page (where it gets downloaded as a spreadsheet), it runs without error, but doesn't bring up the prompt to download the spreadsheet. The JSON has generated without problem (I have made the PHP page create the file on the server, before trying to make it download without creating it).
Here is the JavaScript code that sends the JSON data to the server:
function writeToSpreadsheet()
{
// get the json for #theTable
var tableJSON = tableToJSON("tr:not(#titleRow)");
//alert(tableJSON);
alert("Sending table data to be written to the spreadsheet...");
$.post('/ResearchProject/tableContent/exportTable.php', {'table': tableJSON}).done(
function(response) { alert(((response == '') ? response : (tableJSON.title + ' written to file!')));})
.fail(function (xhr, ajaxOptions, thrownError) { alert("ERROR:" + xhr.responseText+" - "+thrownError); });
}
and here is exportTable.php
<?php
function cleanData(&$str)
{
$str = preg_replace("/\t/", "\\t", $str); // escaping all of the tabs
$str = preg_replace("/\r?\n/", "\\n", $str); // escaping any and all cases of carriage return
// if there is a single double-quote in the string, we wrap the string in quotes, replace every single double-quote with double double-quotes, and
// end with a double-quote
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
// the data is coming from a JSON object that is being sent here
if (isset($_POST['table']))
{
$tableJSON = $_POST['table']; # somehow, this is already a PHP array (exactly the one we need)!!
// get the name of the table from the $tableJSON
$tableName = $tableJSON['title'];
// get the title row from $tableJSON
$titleRow = $tableJSON['titleRow'];
// fix the titleRow
foreach ($titleRow as $heading)
{
$heading = trim(preg_replace('/\s+/', ' ', $heading));
}
// get the rows from $tableJSON
$rows = $tableJSON['rows'];
// form the filename from the tableName
$fileName = $tableName . '.xls';
// here, we download the file without even creating it
header("Content-Disposition: attachment; filename=\"$fileName\"");
header("Content-Type: application/vnd.ms-excel");
// we echo the titleRow first
array_walk($titleRow, 'cleanData');
echo implode(chr(9), $titleRow) . "\r\n";
?>
<script>console.log('Title row written to file.');</script>
<?php
// now we echo the data
foreach($rows as $row)
{
array_walk($row, 'cleanData');
echo implode(chr(9), $row) . "\r\n";
?>
<script>console.log('Data row written to file.');</script>
<?php
}
}
else
{
echo 'You sent me no data :(\n';
}
?>
OK, MikeWarren, how do I test this??
You can test it by selecting a table from the dropdown menu and clicking the "Export table to spreadsheet" button here: http://dinotator.biokdd.org/ResearchProject/tableViewer.php
I am trying to have it where the table that is on the HTML page gets converted into an JSON object, and then downloaded. Thus, I would need to POST the data to the PHP page, right? (Query strings don't work.)

Query strings won't work because you are using jQuery's $.post call which means that your data is sent in the body of the request, as opposed to a query string which is what a GET uses. For JSON you do indeed want to use a POST.
As for what's going wrong, you need to decode your JSON into a PHP array using json_decode. Unfortunately it can't simply handle JSON how it is.
So most likely you'll want to do:
// now a poorly named variable
$tableJSON = json_decode($_POST['table']);
Also, looking at your Ajax, $.post does accept a .fail() listener, but it doesn't pass any error data as part of the callback. So if you want to be able to handle incoming response errors you'll need to use $.ajax:
$.ajax({
type: "POST",
url: "/your/url.php",
dataType: "json",
error: errorCallback
});
Finally, looking at how your code is structured, if you're actually trying to save to file, you're going to need some more logic. Right now, you're just rendering that table, and then returning it as a response which will show up in your done function. You're going to add some more logic in order to make it actually download. This question entails your exact problem.
Good luck!

I have found so much bad advice on the internet about how to solve this problem. One of the answers here also didn't work. :(
I have decided to get advice from a friend of mine, and me and him have decided on this approach:
Have my exportData.php simply write the data to $_SESSION, echo a JSON-encoded "success", and then exit
On exit, on the client-side of things, if "success" has been received, have the JavaScript open up a new tab to a file that I have created called downloadFile.php which actually does the downloading.
Why didn't sending the data between files work?
Downloading data entails setting the right headers and printing the data. When you send data to the file to do this (via AJAX), the buffer that the data is printed to is the one for response. You can see this by saying something like
success: function(response)
{
alert(response);
} and see the data that you "downloaded" not get downloaded, but get printed on-screen.
However, if you go to the file instead of simply passing data to it, your data will download, provided that it has access to the data that you are trying to download. You can see examples of this here: www.the-art-of-web.com/php/dataexport/ . In those examples, the data was "static" (that is, only existing in the scope of that PHP file, until download happened).
We then see that we should let another file handle the downloading. Here is what its contents should look like:
<?php
if (!isset($_SESSION))
session_start();
function cleanData(&$str)
{
$str = preg_replace("/\t/", "\\t", $str); // escaping all of the tabs
$str = preg_replace("/\r?\n/", "\\n", $str); // escaping any and all cases of carriage return
// if there is a single double-quote in the string, we wrap the string in quotes, replace every single double-quote with double double-quotes, and
// end with a double-quote
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
// get the data from $_SESSION
if (isset($_SESSION))
{
$fileName = $_SESSION['fileName'];
$titleRow = $_SESSION['titleRow'];
$rows = $_SESSION['rows'];
// set the excel headers
header("Content-Type: application/vnd.ms-excel");
//header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"$fileName\"");
header("Pragma: no-cache");
header("Expires: 0");
// attempt download
array_walk($titleRow, 'cleanData');
echo implode(chr(9), $titleRow) . "\r\n";
// now we echo the data
foreach($rows as $row)
{
array_walk($row, 'cleanData');
echo implode(chr(9), $row) . "\r\n";
}
}
else
{
die('Problem with session variable. Data could not be sent for download.');
}
exit;
?>
Of course, before doing this, make sure that you have 'fileName', 'titleRow', and 'rows' already written to $_SESSION.
This should help anyone having problem downloading HTML table to Excel spreadsheet via PHP, and the best part is that you don't have to bloat your server by downloading an entire library, for potentially the functionality of one button!!

Related

Data not sending from XMLHttpRequest [duplicate]

I’m trying to receive a JSON POST on a payment interface website, but I can’t decode it.
When I print :
echo $_POST;
I get:
Array
I get nothing when I try this:
if ( $_POST ) {
foreach ( $_POST as $key => $value ) {
echo "llave: ".$key."- Valor:".$value."<br />";
}
}
I get nothing when I try this:
$string = $_POST['operation'];
$var = json_decode($string);
echo $var;
I get NULL when I try this:
$data = json_decode( file_get_contents('php://input') );
var_dump( $data->operation );
When I do:
$data = json_decode(file_get_contents('php://input'), true);
var_dump($data);
I get:
NULL
The JSON format is (according to payment site documentation):
{
"operacion": {
"tok": "[generated token]",
"shop_id": "12313",
"respuesta": "S",
"respuesta_details": "respuesta S",
"extended_respuesta_description": "respuesta extendida",
"moneda": "PYG",
"monto": "10100.00",
"authorization_number": "123456",
"ticket_number": "123456789123456",
"response_code": "00",
"response_description": "Transacción aprobada.",
"security_information": {
"customer_ip": "123.123.123.123",
"card_source": "I",
"card_country": "Croacia",
"version": "0.3",
"risk_index": "0"
}
}
}
The payment site log says everything is OK. What’s the problem?
Try;
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
echo $data["operacion"];
From your json and your code, it looks like you have spelled the word operation correctly on your end, but it isn't in the json.
EDIT
Maybe also worth trying to echo the json string from php://input.
echo file_get_contents('php://input');
If you already have your parameters set like $_POST['eg'] for example and you don't wish to change it, simply do it like this:
$_POST = json_decode(file_get_contents('php://input'), true);
This will save you the hassle of changing all $_POST to something else and allow you to still make normal post requests if you wish to take this line out.
It is worth pointing out that if you use json_decode(file_get_contents("php://input")) (as others have mentioned), this will fail if the string is not valid JSON.
This can be simply resolved by first checking if the JSON is valid. i.e.
function isValidJSON($str) {
json_decode($str);
return json_last_error() == JSON_ERROR_NONE;
}
$json_params = file_get_contents("php://input");
if (strlen($json_params) > 0 && isValidJSON($json_params))
$decoded_params = json_decode($json_params);
Edit: Note that removing strlen($json_params) above may result in subtle errors, as json_last_error() does not change when null or a blank string is passed, as shown here:
http://ideone.com/va3u8U
Use $HTTP_RAW_POST_DATA instead of $_POST.
It will give you POST data as is.
You will be able to decode it using json_decode() later.
Read the doc:
In general, php://input should be used instead of $HTTP_RAW_POST_DATA.
as in the php Manual
$data = file_get_contents('php://input');
echo $data;
This worked for me.
You can use bellow like..
Post JSON like bellow
Get data from php project user bellow like
// takes raw data from the request
$json = file_get_contents('php://input');
// Converts it into a PHP object
$data = json_decode($json, true);
echo $data['requestCode'];
echo $data['mobileNo'];
echo $data['password'];
Quite late.
It seems, (OP) had already tried all the answers given to him.
Still if you (OP) were not receiving what had been passed to the ".PHP" file, error could be, incorrect URL.
Check whether you are calling the correct ".PHP" file.
(spelling mistake or capital letter in URL)
and most important
Check whether your URL has "s" (secure) after "http".
Example:
"http://yourdomain.com/read_result.php"
should be
"https://yourdomain.com/read_result.php"
or either way.
add or remove the "s" to match your URL.
If all of the above answers still leads you to NULL input for POST, note that POST/JSON in a localhost setting, it could be because you are not using SSL. (provided you are HTTP with tcp/tls and not udp/quic)
PHP://input will be null on non-https and if you have a redirect in the flow, trying configuring https on your local as standard practice to avoid various issues with security/xss etc
The decoding might be failing (and returning null) because of php magic quotes.
If magic quotes is turned on anything read from _POST/_REQUEST/etc. will have special characters such as "\ that are also part of JSON escaped. Trying to json_decode( this escaped string will fail. It is a deprecated feature still turned on with some hosters.
Workaround that checks if magic quotes are turned on and if so removes them:
function strip_magic_slashes($str) {
return get_magic_quotes_gpc() ? stripslashes($str) : $str;
}
$operation = json_decode(strip_magic_slashes($_POST['operation']));
I got "null" when I tried to retrieve a posted data in PHP
{
"product_id": "48",
"customer_id": "2",
"location": "shelf", // shelf, store <-- comments create php problems
"damage_types":{"Pests":1, "Poke":0, "Tear":0}
// "picture":"jhgkuignk" <-- comments create php problems
}
You should avoid commenting JSON code even if it shows no errors
I'd like to post an answer that also uses curl to get the contents, and mpdf to save the results to a pdf, so you get all the steps of a tipical use case. It's only raw code (so to be adapted to your needs), but it works.
// import mpdf somewhere
require_once dirname(__FILE__) . '/mpdf/vendor/autoload.php';
// get mpdf instance
$mpdf = new \Mpdf\Mpdf();
// src php file
$mysrcfile = 'http://www.somesite.com/somedir/mysrcfile.php';
// where we want to save the pdf
$mydestination = 'http://www.somesite.com/somedir/mypdffile.pdf';
// encode $_POST data to json
$json = json_encode($_POST);
// init curl > pass the url of the php file we want to pass
// data to and then print out to pdf
$ch = curl_init($mysrcfile);
// tell not to echo the results
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1 );
// set the proper headers
curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Content-Length: ' . strlen($json) ]);
// pass the json data to $mysrcfile
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
// exec curl and save results
$html = curl_exec($ch);
curl_close($ch);
// parse html and then save to a pdf file
$mpdf->WriteHTML($html);
$this->mpdf->Output($mydestination, \Mpdf\Output\Destination::FILE);
In $mysrcfile I'll read json data like this (as stated on previous answers):
$data = json_decode(file_get_contents('php://input'));
// (then process it and build the page source)

JS/PHP: Fetch does not send POST parameter [duplicate]

I’m trying to receive a JSON POST on a payment interface website, but I can’t decode it.
When I print :
echo $_POST;
I get:
Array
I get nothing when I try this:
if ( $_POST ) {
foreach ( $_POST as $key => $value ) {
echo "llave: ".$key."- Valor:".$value."<br />";
}
}
I get nothing when I try this:
$string = $_POST['operation'];
$var = json_decode($string);
echo $var;
I get NULL when I try this:
$data = json_decode( file_get_contents('php://input') );
var_dump( $data->operation );
When I do:
$data = json_decode(file_get_contents('php://input'), true);
var_dump($data);
I get:
NULL
The JSON format is (according to payment site documentation):
{
"operacion": {
"tok": "[generated token]",
"shop_id": "12313",
"respuesta": "S",
"respuesta_details": "respuesta S",
"extended_respuesta_description": "respuesta extendida",
"moneda": "PYG",
"monto": "10100.00",
"authorization_number": "123456",
"ticket_number": "123456789123456",
"response_code": "00",
"response_description": "Transacción aprobada.",
"security_information": {
"customer_ip": "123.123.123.123",
"card_source": "I",
"card_country": "Croacia",
"version": "0.3",
"risk_index": "0"
}
}
}
The payment site log says everything is OK. What’s the problem?
Try;
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
echo $data["operacion"];
From your json and your code, it looks like you have spelled the word operation correctly on your end, but it isn't in the json.
EDIT
Maybe also worth trying to echo the json string from php://input.
echo file_get_contents('php://input');
If you already have your parameters set like $_POST['eg'] for example and you don't wish to change it, simply do it like this:
$_POST = json_decode(file_get_contents('php://input'), true);
This will save you the hassle of changing all $_POST to something else and allow you to still make normal post requests if you wish to take this line out.
It is worth pointing out that if you use json_decode(file_get_contents("php://input")) (as others have mentioned), this will fail if the string is not valid JSON.
This can be simply resolved by first checking if the JSON is valid. i.e.
function isValidJSON($str) {
json_decode($str);
return json_last_error() == JSON_ERROR_NONE;
}
$json_params = file_get_contents("php://input");
if (strlen($json_params) > 0 && isValidJSON($json_params))
$decoded_params = json_decode($json_params);
Edit: Note that removing strlen($json_params) above may result in subtle errors, as json_last_error() does not change when null or a blank string is passed, as shown here:
http://ideone.com/va3u8U
Use $HTTP_RAW_POST_DATA instead of $_POST.
It will give you POST data as is.
You will be able to decode it using json_decode() later.
Read the doc:
In general, php://input should be used instead of $HTTP_RAW_POST_DATA.
as in the php Manual
$data = file_get_contents('php://input');
echo $data;
This worked for me.
You can use bellow like..
Post JSON like bellow
Get data from php project user bellow like
// takes raw data from the request
$json = file_get_contents('php://input');
// Converts it into a PHP object
$data = json_decode($json, true);
echo $data['requestCode'];
echo $data['mobileNo'];
echo $data['password'];
Quite late.
It seems, (OP) had already tried all the answers given to him.
Still if you (OP) were not receiving what had been passed to the ".PHP" file, error could be, incorrect URL.
Check whether you are calling the correct ".PHP" file.
(spelling mistake or capital letter in URL)
and most important
Check whether your URL has "s" (secure) after "http".
Example:
"http://yourdomain.com/read_result.php"
should be
"https://yourdomain.com/read_result.php"
or either way.
add or remove the "s" to match your URL.
If all of the above answers still leads you to NULL input for POST, note that POST/JSON in a localhost setting, it could be because you are not using SSL. (provided you are HTTP with tcp/tls and not udp/quic)
PHP://input will be null on non-https and if you have a redirect in the flow, trying configuring https on your local as standard practice to avoid various issues with security/xss etc
The decoding might be failing (and returning null) because of php magic quotes.
If magic quotes is turned on anything read from _POST/_REQUEST/etc. will have special characters such as "\ that are also part of JSON escaped. Trying to json_decode( this escaped string will fail. It is a deprecated feature still turned on with some hosters.
Workaround that checks if magic quotes are turned on and if so removes them:
function strip_magic_slashes($str) {
return get_magic_quotes_gpc() ? stripslashes($str) : $str;
}
$operation = json_decode(strip_magic_slashes($_POST['operation']));
I got "null" when I tried to retrieve a posted data in PHP
{
"product_id": "48",
"customer_id": "2",
"location": "shelf", // shelf, store <-- comments create php problems
"damage_types":{"Pests":1, "Poke":0, "Tear":0}
// "picture":"jhgkuignk" <-- comments create php problems
}
You should avoid commenting JSON code even if it shows no errors
I'd like to post an answer that also uses curl to get the contents, and mpdf to save the results to a pdf, so you get all the steps of a tipical use case. It's only raw code (so to be adapted to your needs), but it works.
// import mpdf somewhere
require_once dirname(__FILE__) . '/mpdf/vendor/autoload.php';
// get mpdf instance
$mpdf = new \Mpdf\Mpdf();
// src php file
$mysrcfile = 'http://www.somesite.com/somedir/mysrcfile.php';
// where we want to save the pdf
$mydestination = 'http://www.somesite.com/somedir/mypdffile.pdf';
// encode $_POST data to json
$json = json_encode($_POST);
// init curl > pass the url of the php file we want to pass
// data to and then print out to pdf
$ch = curl_init($mysrcfile);
// tell not to echo the results
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1 );
// set the proper headers
curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Content-Length: ' . strlen($json) ]);
// pass the json data to $mysrcfile
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
// exec curl and save results
$html = curl_exec($ch);
curl_close($ch);
// parse html and then save to a pdf file
$mpdf->WriteHTML($html);
$this->mpdf->Output($mydestination, \Mpdf\Output\Destination::FILE);
In $mysrcfile I'll read json data like this (as stated on previous answers):
$data = json_decode(file_get_contents('php://input'));
// (then process it and build the page source)

After sending a Javascript POST request, how to retreive the data in php? [duplicate]

I’m trying to receive a JSON POST on a payment interface website, but I can’t decode it.
When I print :
echo $_POST;
I get:
Array
I get nothing when I try this:
if ( $_POST ) {
foreach ( $_POST as $key => $value ) {
echo "llave: ".$key."- Valor:".$value."<br />";
}
}
I get nothing when I try this:
$string = $_POST['operation'];
$var = json_decode($string);
echo $var;
I get NULL when I try this:
$data = json_decode( file_get_contents('php://input') );
var_dump( $data->operation );
When I do:
$data = json_decode(file_get_contents('php://input'), true);
var_dump($data);
I get:
NULL
The JSON format is (according to payment site documentation):
{
"operacion": {
"tok": "[generated token]",
"shop_id": "12313",
"respuesta": "S",
"respuesta_details": "respuesta S",
"extended_respuesta_description": "respuesta extendida",
"moneda": "PYG",
"monto": "10100.00",
"authorization_number": "123456",
"ticket_number": "123456789123456",
"response_code": "00",
"response_description": "Transacción aprobada.",
"security_information": {
"customer_ip": "123.123.123.123",
"card_source": "I",
"card_country": "Croacia",
"version": "0.3",
"risk_index": "0"
}
}
}
The payment site log says everything is OK. What’s the problem?
Try;
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
echo $data["operacion"];
From your json and your code, it looks like you have spelled the word operation correctly on your end, but it isn't in the json.
EDIT
Maybe also worth trying to echo the json string from php://input.
echo file_get_contents('php://input');
If you already have your parameters set like $_POST['eg'] for example and you don't wish to change it, simply do it like this:
$_POST = json_decode(file_get_contents('php://input'), true);
This will save you the hassle of changing all $_POST to something else and allow you to still make normal post requests if you wish to take this line out.
It is worth pointing out that if you use json_decode(file_get_contents("php://input")) (as others have mentioned), this will fail if the string is not valid JSON.
This can be simply resolved by first checking if the JSON is valid. i.e.
function isValidJSON($str) {
json_decode($str);
return json_last_error() == JSON_ERROR_NONE;
}
$json_params = file_get_contents("php://input");
if (strlen($json_params) > 0 && isValidJSON($json_params))
$decoded_params = json_decode($json_params);
Edit: Note that removing strlen($json_params) above may result in subtle errors, as json_last_error() does not change when null or a blank string is passed, as shown here:
http://ideone.com/va3u8U
Use $HTTP_RAW_POST_DATA instead of $_POST.
It will give you POST data as is.
You will be able to decode it using json_decode() later.
Read the doc:
In general, php://input should be used instead of $HTTP_RAW_POST_DATA.
as in the php Manual
$data = file_get_contents('php://input');
echo $data;
This worked for me.
You can use bellow like..
Post JSON like bellow
Get data from php project user bellow like
// takes raw data from the request
$json = file_get_contents('php://input');
// Converts it into a PHP object
$data = json_decode($json, true);
echo $data['requestCode'];
echo $data['mobileNo'];
echo $data['password'];
Quite late.
It seems, (OP) had already tried all the answers given to him.
Still if you (OP) were not receiving what had been passed to the ".PHP" file, error could be, incorrect URL.
Check whether you are calling the correct ".PHP" file.
(spelling mistake or capital letter in URL)
and most important
Check whether your URL has "s" (secure) after "http".
Example:
"http://yourdomain.com/read_result.php"
should be
"https://yourdomain.com/read_result.php"
or either way.
add or remove the "s" to match your URL.
If all of the above answers still leads you to NULL input for POST, note that POST/JSON in a localhost setting, it could be because you are not using SSL. (provided you are HTTP with tcp/tls and not udp/quic)
PHP://input will be null on non-https and if you have a redirect in the flow, trying configuring https on your local as standard practice to avoid various issues with security/xss etc
The decoding might be failing (and returning null) because of php magic quotes.
If magic quotes is turned on anything read from _POST/_REQUEST/etc. will have special characters such as "\ that are also part of JSON escaped. Trying to json_decode( this escaped string will fail. It is a deprecated feature still turned on with some hosters.
Workaround that checks if magic quotes are turned on and if so removes them:
function strip_magic_slashes($str) {
return get_magic_quotes_gpc() ? stripslashes($str) : $str;
}
$operation = json_decode(strip_magic_slashes($_POST['operation']));
I got "null" when I tried to retrieve a posted data in PHP
{
"product_id": "48",
"customer_id": "2",
"location": "shelf", // shelf, store <-- comments create php problems
"damage_types":{"Pests":1, "Poke":0, "Tear":0}
// "picture":"jhgkuignk" <-- comments create php problems
}
You should avoid commenting JSON code even if it shows no errors
I'd like to post an answer that also uses curl to get the contents, and mpdf to save the results to a pdf, so you get all the steps of a tipical use case. It's only raw code (so to be adapted to your needs), but it works.
// import mpdf somewhere
require_once dirname(__FILE__) . '/mpdf/vendor/autoload.php';
// get mpdf instance
$mpdf = new \Mpdf\Mpdf();
// src php file
$mysrcfile = 'http://www.somesite.com/somedir/mysrcfile.php';
// where we want to save the pdf
$mydestination = 'http://www.somesite.com/somedir/mypdffile.pdf';
// encode $_POST data to json
$json = json_encode($_POST);
// init curl > pass the url of the php file we want to pass
// data to and then print out to pdf
$ch = curl_init($mysrcfile);
// tell not to echo the results
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1 );
// set the proper headers
curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Content-Length: ' . strlen($json) ]);
// pass the json data to $mysrcfile
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
// exec curl and save results
$html = curl_exec($ch);
curl_close($ch);
// parse html and then save to a pdf file
$mpdf->WriteHTML($html);
$this->mpdf->Output($mydestination, \Mpdf\Output\Destination::FILE);
In $mysrcfile I'll read json data like this (as stated on previous answers):
$data = json_decode(file_get_contents('php://input'));
// (then process it and build the page source)

How to use AJAX and JSON to get data returned from a PHP file

For starters this website is being run on a Debian machine.
I have a SQLite3 database that has current news articles in it. I am trying to use PHP to query the database for these articles, and pass it as JSON to AJAX, so it can be displayed on my webpage. Right now nothing is being shown and I don't know where the error is.
Here is the PHP code to get the information from the database:
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('website.db');
}
}
$db = new MyDB();
$result = $db->query('SELECT * FROM news');
echo json_encode($result);
?>
Here is the JavaScript where the AJAX is located:
<script type="text/javascript">
function getNews()
{
console.log("firstStep");
$(document).ready(function()
{
console.log("secondStep");
$.getJSON("http://localhost/getNews.php",function(result){
console.log("thirdStep");
$('news').append(result); // display result
});
});
}
I think the error is occurring around $.getJSON("http://localhost/getNews.php",function(result), as in the console, thirdStep is never being outputted.
This is the HTML it should be appending to:
<div id = "newsEntry"> <news> test </news> </div>
Any help would be appreciated.
To find out what's going on, you might want to add an error handler:
$(document).ready(function() {
$.ajax({
url: "http://localhost/getNews.php",
dataType: "json",
success: function(result) {
console.log("thirdStep");
},
error: function(err) {
alert(err);
}
});
})
By default, the web server serves content as application/html. So when you simply echo a JSON string, it's treated like text on a html page. To really return JSON from your server, you need to specifically set it.
Include this line before your echo:
header('Content-Type: application/json; charset=utf-8');
Edit
On inspection of you PHP code, you are missing one line. Note that $db->query() returns you an SQLite3Result. You need to call:
$array = $result->fetchArray(SQLITE3_ASSOC); // get an associative array first
$json = json_encode($array);
header('Content-Type: application/json; charset=utf-8');
echo $json

Improve Page Performance, save PHP array on server?

is it possible to store a PHP-array to my server, right now it always gets created when someone reloads the page from a CSV file but that is unnecessary since the file only chances after each hour.
ATM, the page takes like 9 seconds to load, which is quite long. The CSV file has 10k+ rows with 9 elements per row, so it would be really good for performance if the server didn't have to process 100k elements for each user.
I already have a cronjob for downloading the csv file so it would be good if the parse command would be executed after the download finished, only once per hour.
cronjob:
<?php
function download_remote_file($file_url, $save_to) {
$content = file_get_contents($file_url);
file_put_contents($save_to, $content);
}
download_remote_file(<url here>, realpath(".") . '/dump.csv');
?>
and this happens with every reload of the page:
1st: Parse data to array
$url = 'dump.csv';
$csvData = file_get_contents($url);
$lines = explode(PHP_EOL, $csvData);
$array = array();
foreach ($lines as $line) {
$line = str_replace("\\", "\", $line);
$line = str_replace("#", "#", $line);
$array[] = str_getcsv($line);
2nd: pass array to Javascript
var array = <?php echo json_encode( $array ) ?>;
3rd: create HTML table
//some code
4th: initialise data table plugin
$(document).ready( function () {
createtable();
$('#scoreboard').DataTable( {
"iDisplayLength": 50,
language: {
decimal: ".",
},
"lengthMenu": false,
"bLengthChange": false
} );
} );
Is there something that could be done faster?
Like, as mentioned, save the php array server-side or maybe saving the JS array with the HTML table somehow?
-Innerwolf
After you parse your CSV, do this:
$file = fopen('/tmp/output.js', 'w');
fwrite($file, '<script type="text/javascript">');
fwrite($file, 'var array =');
fwrite($file, json_encode( $array ));
fwrite($file, ';');
fwrite($file, '</script>');
fclose($file);
copy('/path/to/script.js', '/path/to/script.js.bak');
move('/tmp/output.js', '/path/to/script.js');
Then, later on when you are outputting the HTML, you just need to stick in a:
<script type="text/javascript" src="/scripts/script.js">
in the header. People's browsers should cache it properly too. Note the copy and move -- you don't strictly need to make a backup copy, but you MUST use a move() to replace the 'live' script -- move() is atomic, more or less, and won't result in anyone getting a half-file.
Also, note that you'll need write permissions to where the script is -- there are ways to keep this pretty secure (not letting your PHP script write all over the hard drive), but that's out of scope here.
Since you mention getting the data on an hourly basis I suggest the following:
grab the CSV file with cron and store the data in a database on an hourly basis
configure your data tables component to use server side data
This way you won't force every user to download the entire array at once on every first page load.
The server side script only fetches the number of records that need to be displayed on that particular page in the table.

Categories

Resources