Saving HTML table to CSV on server from client side - javascript

I'm trying to read a .dat file (it's a CSV with delimiter';') and convert it into a table and is done in PHP and is as follows:
<table id='sol'>
<?php
echo "<html><body>";
$f = fopen("/var/www/html/uploads/data_old.dat", "r");
$var = 0;
/* Writes the CSV to table in the page*/
while (($line = fgetcsv($f, 0, ';')) !== false) {
echo "<tr>";
foreach ($line as $cell) {
if ($var < 36) {
echo "<th>" . htmlspecialchars($cell) . "</th>";
$var = $var + 1;
}
else {
echo "<td><div contenteditable>" . htmlspecialchars($cell) . "</div></td>";
}
}
echo "</tr>";
}
fclose($f);
echo "</body></html>";
?>
</table>
Now after editing the values in the table, I need to save this table on the server. Currently, I can download the table in .dat using a script written in JS as below:
// Quick and simple export target #table_id into a csv
function download_table_as_csv(table_id, separator = ';') {
// Select rows from table_id
var rows = document.querySelectorAll('table#' + table_id + ' tr');
// Construct csv
var csv = [];
for (var i = 0; i < rows.length; i++) {
var row = [], cols = rows[i].querySelectorAll('td, th');
for (var j = 0; j < cols.length; j++) {
// Clean innertext to remove multiple spaces and jumpline (break csv)
var data = cols[j].innerText.replace(/(\r\n|\n|\r)/gm, '').replace(/(\s\s)/gm, ' ')
// Escape double-quote with double-double-quote
data = data.replace(/"/g, '""');
// Push escaped string
row.push('"' + data + '"');
}
csv.push(row.join(separator));
}
var csv_string = csv.join('\n');
// Download it
var filename = 'data_new' + '.dat';
var link = document.createElement('a');
link.style.display = 'none';
link.setAttribute('target', '_blank');
link.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv_string));
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
I'm fairly new to this and any help is highly appreciated.

I might not understand the question here, but I think its something like "I get a csv file from a user - how to display file's fields as an HTML table, and then setup a download link for newly editted file"
If that sounds correct, this is probably what you want.
You are correctly displaying the CSV as an HTML table (as far as I can tell).
if htmlspecialchars(..) changes the characters emitted from data_old.dat then we start writing a new CVS file where we'll place the changes emitted by htmlspacechars(..) - and you write in the delimiter yourself by adding ; (as you noted).
$f_ = fopen("/var/www/html/uploads/data_new.dat", "w");
And which ever file we wish the user to download, just place it inside an <a href='...'> tag.
<?php echo "<a href='uploads/data_new.data'>download</a>" ?>
Furthermore (Getting user edits):
While the example above tells us how to setup the backend for the user downloading the file, - it doesn't outline a way for the user to commit edits, and the backend to know about it.
To do allow the server to know about user edits, as mentioned in the comments AJAX is the way to go for php.
AJAX is Javascript sending XML (body) notation to the backend as an http request. The way it works is described in the image below.
AJAX is accessed by javascript in the browser (hey the where the user is!)
var xhttp = new XMLHttpRequest(); // setup object
// hook function
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// this is ran after we get an OK from the server.
// after they've committed a change
}
};
// setup request
xhttp.open("GET", "link/to/your/website", true)
xhttp.send(); // send it
AJAX playground
So far this is pretty vague outlining of what it is, now lets see how we can use it.
So the idea being that when a user changes a field in the table, we run some javascript to send an AJAX request. Specifying what they changed.
The server gets the request, updates the changes on the backend, and then sends OK back to the client.
Hope this helps.

Related

Output PDF from database via PHP and display it via Javascript

I'm trying to display a PDF file that I stored in my database as a BLOB file. Although I have tried a couple of ways I still can't seem to get it right.
Here is how I (try to) download a PDF file from my database:
function fillArrays(){
$idArray = array();
$sql = "SELECT oglas_id,slika,prioriteta FROM deska WHERE deska.datumz <= CURRENT_DATE AND deska.datumk >= CURRENT_DATE;";
$result = mysqli_query($GLOBALS['conn'],$sql);
$resultCheck = mysqli_num_rows($result);
if($resultCheck>0){
while($row = mysqli_fetch_assoc($result)){
array_push($GLOBALS['idArray'],$row['oglas_id']);
$b64Doc = chunk_split(base64_encode(file_get_contents($row['slika']))); // THIS LINE!
$file = "data:application/pdf;base64,".$b64Doc; // THIS LINE!
array_push($GLOBALS['imgArray'],$file); // THIS LINE!
array_push($GLOBALS['prArray'],$row['prioriteta']);
}
}else{
die("Oops there seems to be an error(arr)");
}
}
The code I've marked "THIS LINE!" should put all my PDF files from the database into an array of PDF files called $imgArray. Then I json_encode the array and assign it to the imgArray variable in JavaScript:
var imgArray = <?php echo json_encode($imgArray) ?>;
And finally, I try to display the same PDF file 4 times in a table created via JavaScript. (I call createTable() in main PHP file):
var idArray = window.idArray;
var imgArray = window.imgArray;
var prArray = window.prArray;
var screenH = screen.height/2.1;
var screenW = screen.width/2.1;
var tdW;
var tdH;
function createTables(){
if(idArray.length>2){
rows=2;
cols=2;
tdW='100%';
tdH='100%';
}else if(idArray.length==2){
rows=1;
cols=2;
tdW='100%';
tdH='100%';
}else if(idArray.length==1){
tdW='100%';
tdH='100%';
}
var table = '';
for(var r=0;r<rows;r++){
table += '<tr>';
for(var c=0;c<cols;c++){
table += '<td style="max-width:'+tdW+';max-height:'+tdH+';" id="c'+c+r+'">';
table += '<embed src="'+imgArray[1]+'" type="application/pdf" style="max-height:'+screenH+';max-width:'+screenW+';">';
table += '</td>';
}
table += '</tr>';
}
document.write("<table>"+table+"</table>");
}
See at the bottom of the code where I try to embed the pdf file. Output on the site is this:
The language is Slovene and it says that the PDF file is corrupted.
You json_encode the data server-side but then don't call JSON.parse on the client-side. This means you are outputting JSON-encoded data directly into the <script src=""> attribute.
Change the PHP encoding process to remove unnecessary function calls:
$b64Doc = base64_encode($row['slika']);
Then you'll need to modify your JavaScript to correctly parse the JSON. Something like:
var imgArray = JSON.parse('<?= json_encode($imgArray); ?>');
for (var i = 0; i < imgArray.length; i++) {
table += '<embed src="' + imgArray[i] + '"></embed>';
}

JSON Newbie - permanently saving values to JSON between browser reloads

I have an AJAX poll based on this tutorial: http://www.w3schools.com/php/php_ajax_poll.asp
However, instead of writing the poll entries from the HTML radio button to an array in a text file (as outlined in the tutorial). I would like to write to a JSON file. At the moment the values from the radio button entry are sent to the JSON, but the file does not retain the value between browser refreshes. I think that this is probably an issue with my syntax or encoding - the server should have the correct permissions to write to the file. Any tips are greatly appreciated.
<?php $vote = $_REQUEST['vote'];
//get content of json
$filename = "poll.json";
$poll = file_get_contents($filename);
$json = json_decode($poll);
//put content in array
$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];
if ($vote == 0) {
$yes = $yes + 1;
}
if ($vote == 1) {
$no = $no + 1;
}
//insert votes to json file
$insertvote = $yes."||".$no;
$fp = fopen($filename,"w");
fputs($fp,$insertvote);
$poll = json_encode($json);
fclose($fp);?>
At the moment the result is either:
{1||}
or
{||1} in the JSON file, I can't figure out how to save the values the way that they were saved to the .txt file version (as outlined here: http://www.w3schools.com/php/php_ajax_poll.asp)
Update
So based on the excellent advice I received I am much closer. I found that "w" was the correct option for the php as "a+" appended data in the JSON rather than updating the existing values.
I now have a JSON file which is updating the values that are added through the html radio buttons.
So the result looks like: [3,4]
AKA 3 votes from option 1 and 4 votes for option 2
Several issues:
You JSON format is not JSON. Values like 0||1 are not JSON, and so json_encode on it will fail. One of the benefits of true JSON is that you don't have to juggle with delimiters like ||.
The $content variable is nowhere initialised.
You encode something as JSON near the end, but don't do anything with it.
You call a variable $json when you intend to store decoded JSON in it. That is really confusing. Don't call such a variable $json.
Here is some alternative code:
$vote = $_REQUEST['vote'];
//get content of json
$filename = "poll.json";
if (!file_exists($filename)) { // First time ever
$poll = [0, 0];
} else {
$poll = json_decode(file_get_contents($filename));
if (!$poll) $poll = [0, 0];
}
// increment counter for vote
$poll[$vote] += 1;
//insert votes to json file
file_put_contents($filename, json_encode($poll));
Your problem is at this line:
$fp = fopen($filename,"w");
According to the manual, mode "w":
places the file pointer at the beginning of the file and truncate the file to zero length
In other words: Each request overrides the whole file with it's contents.
To fix this, use mode "a+".
$fp = fopen($filename,"w");
Probably you change code and this is undefined:
$content[0]
In
$array = explode("||", $content[0]);
Source Is:
<?php
$vote = $_REQUEST['vote'];
//get content of textfile
$filename = "poll_result.txt";
$content = file($filename);
//put content in array
$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];
if ($vote == 0) {
$yes = $yes + 1;
}
if ($vote == 1) {
$no = $no + 1;
}
//insert votes to txt file
$insertvote = $yes."||".$no;
$fp = fopen($filename,"w");
fputs($fp,$insertvote);
fclose($fp);
?>

Issue with PHP and Javascript when building auto suggest text box

I'm trying to build a simple auto suggest input bar that connects to a MySql database and retrieves data. The issue that I'm running into is that when I type in the name of an object that I know exists in the databse, the text bar doesn't return any results, instead it just provides me with an empty dropdown box.
The best I can tell, the issue has to do with the javascript that is used within the PHP portion of the code. Unfortunately, I can't seem to figure out why it's causing an issue.
<?php
mysql_connect("host", "user", "passsword") OR DIE ('Unable to connect to database! Please try again later.');
mysql_select_db('DBName');
$query = 'SELECT Device_type FROM Device';
$result = mysql_query($query);
$counter = 0;
echo"<script type='text/javascript'>";
echo"this.nameArray = new Array()";
if($result) {
while($row = mysql_fetch_array($result)) {
echo("this.nameArray" .$row ['Device_type'] . "';");
$counter += 1;
}
}
echo("</script>");
?>
When I take out the echo"<script type='text/javascript'>"; and echo"this.nameArray = new Array()"; then It displays the Device_type content on the top of the page when the page is loaded. This obviously isn't what I want, but it does prove that the database connection is at least set up correctly. Since this chunk of PHP is referring to some javascript, I will also prove the function in which it's referring to.
function doSuggestions(text) {
var input = text;
//window.alert(text);
var inputLength = input.toString().length;
var code = "";
var counter = 0;
while(counter < this.nameArray.length) {
var x = this.nameArray[counter]; // avoids retyping this code a bunch of times
if(x.substr(0, inputLength).toLowerCase() == input.toLowerCase()) {
code += "<div id='" + x + "'onmouseover='changeBG(this.id);' onMouseOut='changeBG(this.id);' onclick='doSelection(this.innerHTML)'>" + x + "</div>";
}
counter += 1;
}
if(code == "") {
outClick();
}
document.getElementById('divSuggestions').innerHTML = code;
document.getElementById('divSuggestions').style.overflow='auto';
}
Any suggestions as to why the suggestion box isn't providing suggestions when I start typing? If I type A into the text box, the suggestion box should appear showing me all items in the database that start with A.
there are some errors in your js strings
`echo"var nameArray = new Array()";`
`echo("nameArray.push('" .$row ['Device_type'] . "');");`
that way you'll push device types into the nameArray var.

Recognising strings between certain tags in external file -PHP

I am new to php, and want a script that can recognise text between certain tags in an external file.
I managed to find an answer here, that recognises the text in tags in a set string, but I am unsure of how to get the file to recognise the tags in an external text file.
PHP:
<?php
function innerh($string, $start, $end){
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
$fullstring = "The <tag>Output</tag>"; // this is the string
$parsed = innerh($fullstring, "<tag>", "</tag>");
echo $parsed;
?>
External File:
<tag>This text</tag> <!-- This is the target -->
Similar to what you are already doing. Currently you are making a string with that tag and when you want to read it from a file you can simply do
$fullstring = file_get_contents('your-file.html');
No other changes are required. You might need to provide full path of that file but that's about it.
That function reads a file and returns its contents in a string which you can save in your variable just like you built the variable manually.
Your code must be somthing like this:
<?php
function innerh($string, $start, $end){
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
// Open a file with READ-ONLY flag ("r") and start of begining for read.
// See: http://php.net/manual/en/function.fopen.php
$fp = fopen("/path/to/file", "r");
// Check that file is opened and ready for read
if ($fp) {
// Until we have content on file, we resume reading
while (!feof($fp)) {
// Read from file, line by line.
// See: http://php.net/manual/en/function.fgets.php
$line = fgets($fp);
// Process line by line and print result
$parsed = innerh($line, "<tag>", "</tag>");
echo $parsed;
/* If your input file is a file without a new line or something like it,
just add a `$line = '';` before while line and change read line with
`$line .= fgets($fp);`, also remove process line and print line. After
that your file is on $line variable ;). */
}
}
?>

I am unable to pass on the value to a PHP script from a javascript using JSON

What is it that I am doing wrong? the value of myid1 is not being accepted by my PHP script. My Javascript code is below followed by my PHP script. Please help.
Javascript code
function generaterepno(selectedid) {
var idnum=selectedid;
var idnum1=idnum.split(":",1);
var text='[{"myid1":idnum1}]';
var httpc = new XMLHttpRequest();
var url = "reportnumber.php";
httpc.open("POST", url, true); // sending as POST
httpc.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
httpc.setRequestHeader("Content-Length", text.length);
httpc.onreadystatechange = function() {
if(httpc.readyState == 4 && httpc.status == 200) {
alert(httpc.responseText);
var myArr = JSON.parse(httpc.responseText);
}
httpc.send(text);
document.getElementById('genno').value=idnum1;
}
My PHP is as follows-
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$mynewid=$_POST["myid1"];
$mynewid=strip_tags($mynewid);
include("inc_con.php");
$myquery="SELECT MAX(report_number) AS mrepno FROM childreports WHERE child_id='$mynewid' ORDER BY report_number";
$myresult=mysql_query($myquery);
if(!$myresult) {
$outp = '[{"reportn":"0"}]';
echo ($outp);
die('records do not exist');
}
$outp = "[";
while($rm = mysql_fetch_array($myresult)) {
$outp .= '{"reportn":"'.$rm["mrepno"].'"}';
}
$outp .="]";
mysql_close($con);
echo ($outp);
?>
I am a newbie to JSON and Javascript. Been trying to learn it on my own by reading. The alert message of the responseText is displaying a notice that myid1 is not defined. Also in my Javascript the HTML id genno is supposed to get the the return value from PHP code that is the max report number as obtained from the SQL query. Once I get reportn variable with some value I can JSON parse it and put it in the genno id but my problem is sending the myid1 value properly to my PHP script reportnumber.php.
Can someone help please? Thanks!
After prompt and great help from Kyle I made some changes in my Javascript function as follows and my query appears in the comments section below.
function myFunction(arr) {
var tempans = arr.reportn;
var myans = 0;
if(tempans.length == 0) {
var asknum = prompt('Enter previous report number:');
myans = parseInt(asknum)+1;
} else {
myans = parseInt(tempans)+1;
}
document.getElementById('genno').value=myans;
}
Why am i prompted TWICE for a user input?
You have a problem here. var text='[{"myid1":idnum1}]'; is not valid JSON because you're trying to put the variable idnum1 inside the string. It would be easier to set it in an object and then use JSON.stringify() to convert it to JSON.
var text = JSON.stringify({"myid1": idnum1});
In PHP, you then need to decode it from the request body as it won't be set in $_POST.
$contents = json_decode(file_get_contents("php://input"), true);
$myNewId = $contents['myid1'];

Categories

Resources