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>';
}
Related
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.
I am trying to make an application in which I use the simple while loop in PHP file to show the record. the code in product.php is here: How to use this in javascript. I need to call the in the java file in the same way.
$sql2 = "SELECT * FROM product";
$result2 = $DBcon->query($sql2);
if ($result2->num_rows > 0) {
// output data of each row
while($row2 = $result2->fetch_assoc()) {
$pname = $row2["product_name"];
$timg = $row2["thumb_img"];
$pimg = $row2["product_img"];
if(!empty($timg)){
echo '<img src="adminpanel/upload/product/'.$timg.'" alt="'.$pname.'" title="'.$pname.'">';
}else{
echo '<img src="adminpanel/upload/product/'.$pimg.'" alt="'.$pname.'" title="'.$pname.'">';
}
}
}
If you need to call something in javascript from php in the same file you could do something like this
var h=<?php $h ?>;
So I have this problem where i define a table(may not be the most effective way of doing it but that is not the problem) which works out just fine for me. However, when I try to change the contents of tabledata assigned with its ID, nothing happnes, no new image is displayed instead of the one that has been assigned to id at the creation of the table.
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'+r+''+c+'">';
table += '<img style="max-height:'+screenH+';max-width:'+screenW+';" src="'+imgArray[2]+'"';
table += '</td>';
}
table += '</tr>';
}
document.write("<table>"+table+"</table>");
}
function addImage(r,c){
document.getElementById('c'+r+''+c).innerHTML('<img style="max-height:'+screenH+';max-width:'+screenW+';" src="'+imgArray[1]+'"');
}
everything works fine untill I try to change the image in particular column of the particular row so it would begin displaying instead of the first picture assigned to the cell with its' id. id of the cell: 'c00' (the problem is the function addImage().. this "innerHTML" stuff doesnt work for me..).
I really don't get it...
Thats the main php file:
<?php
include "includes/connect.php";
?>
<html>
<head>
<link type="text/css" rel="stylesheet" href="includes/style.css">
<title>Cablex-T OG</title>
</head>
<?php
$idArray = array();
$imgArray = array();
$prArray = array();
fillArrays();
?>
<script>
var idArray = <?php echo json_encode($idArray) ?>;
var imgArray = <?php echo json_encode($imgArray) ?>;
var prArray = <?php echo json_encode($prArray) ?>;
</script>
<script src="includes/script.js"></script>
<body>
<script>
createTables();
addImage(1,2);
</script>
</body>
</html>
function addImage(){
document.getElementById('c'+r+''+c).innerHTML('<img style="max-height:'+screenH+';max-width:'+screenW+';" src="'+imgArray[1]+'"');
}
Tis function depends on values of r and c but those values don't seem to be passed to the function.
Do you maybe want to define it with:
function addImage(someR, and Some c){
//...
}
and then call:
addImage(1, 2)
I've created a element populator, which takes certain elements, wraps them in HTML tags and appends them to a container. The problem I have, which is more of nuisance if anything, is for every image to be loaded it has to be input automatically. Is there a way to retrieve all images from a folder and load them into an array?
I have this code, which works, but with manual input:
$(window).on('load', function () {
var gallery = document.getElementById("grid");
var images = [
"./imgs/galeria/0.jpg",
"./imgs/galeria/1.jpg",
"./imgs/galeria/2.jpg",
"./imgs/galeria/3.jpg",
"./imgs/galeria/4.jpg",
"./imgs/galeria/7.jpg",
"./imgs/galeria/6.jpg",
"./imgs/galeria/5.jpg",
"./imgs/galeria/8.jpg",
"./imgs/galeria/9.jpg",
"./imgs/galeria/10.jpg",
"./imgs/galeria/11.jpg",
"./imgs/galeria/12.jpg",
"./imgs/galeria/13.jpg",
"./imgs/galeria/14.jpg",
"./imgs/galeria/15.jpg",
"./imgs/galeria/16.jpg",
"./imgs/galeria/17.jpg",
"./imgs/galeria/18.jpg",
"./imgs/galeria/19.jpg",
"./imgs/galeria/20.jpg"
];
for (var i = 0; i < images.length; i++) {
var thumbnailWrapper = document.createElement("div");
thumbnailWrapper.className = "thumbnail-wrapper";
var thumbnail = document.createElement("div");
thumbnail.className = "thumbnail";
thumbnail.dataset.source = "./imgs/galeria/" + i + ".jpg";
thumbnailWrapper.appendChild(thumbnail);
gallery.appendChild(thumbnailWrapper);
}
var thumb = document.getElementsByClassName('thumbnail');
// console.log(thumb);
for (j = 0; j < images.length; j++) {
// $(thumb[j]).attr('src', images[j]);
$(thumb[j]).css('background-image', 'url(./imgs/galeria/thumbs/' + j + 'tbm.jpg)');
// console.log(j);
// console.log(images[j]);
}
You can see the script in action in this website I made in the "galeria" section.
EDIT: maybe something with ajax? I wanted to keep php out of the equation
EDIT2: I would like to make it with ajax, and this is now the correct code
You can't use client-side JavaScript to scan a folder on a server. If you don't know what files the folder contains, then AJAX alone doesn't even work.
You have to use server-side code, such as PHP, to find all the files in the folder, and them deliver them somehow to the client. That is the only way I see.
This approach could work:
$images = glob('imgs/galeria/*.jpg');
echo '<div id="grid">';
foreach ($images as $key => $image) {
echo '<div class="thumbnail-wrapper">';
echo '<div
class="thumbnail"
data-source="' . $image . '"
style="background-image: url(imgs/galeria/thumbs/' . $key . 'tbm.jpg)"
></div>';
echo '</div>';
}
echo '</div>';
I hope this works like your JavaScript code does.
I have not been able to find a simple example of ajax with single variable, everything on here is made way too complicated for an AJAX beginner. I've watched about 4 different YouTube videos on the topic, but can't seem to get it right.
I have the src of an image in a variable like so with a JavaScript..
<img alt="" src="blah.jpg" style="height: 276px; width: 200px" id="imgClickAndChange1" onclick="changeImage(this)" />
<script language="javascript">
function changeImage(imagePass) {
var num = Math.floor((Math.random() * 48) + 1);
var n = num.toString();
var numImg = n.concat(".jpeg");
var string = "/Images/Folder/"
var final = string.concat(numImg);
imagePass.src = final;
//(this is where I want to pass the variable imagePass.src or "final" to a php script w/ Ajax)
Here is my php script:
<?php>
include_once "code.php"; //connecting to database
$s = (this is where I want the variable to be posted);
$temp = explode('/', $s);
$temp2 = explode('.', $temp[count($temp) - 1]); //this is getting the variable I want from the variable sent(which is actually a number)
$float = (int)$temp2; //changing the number (which is a string) to an int
mysql_query("UPDATE Variable SET `upVote` = `upVote`+1 WHERE id= (variable here)) " //Making a row in my database w/ the id of the variable add 1 to the count
?>
How would I go about posting and sending this w/out a page refresh? AJAX is really confusing me so a working implementation to get me started on this would be great, Thanks a lot.
//Let's just assume the php page where the script is located is called 'hello.php'
To use ajax, try this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function changeImage(imagePass) {
var num = Math.floor((Math.random() * 48) + 1);
var n = num.toString();
var numImg = n.concat(".jpeg");
var string = "/Images/Folder/"
var final = string.concat(numImg);
imagePass.src = final;
$.ajax({
url : 'hello.php',
type: 'post',
data : {'final':final},
success: function()
{
alert('Success!');
}
});
}
</script>
PHP script (hello.php):
<?php>
include_once "code.php"; //connecting to database
$s = $_POST['final'];
$temp = explode('/', $s);
$temp2 = explode('.', $temp[count($temp) - 1]); //this is getting the variable I want from the variable sent(which is actually a number)
$float = (int)$temp2; //changing the number (which is a string) to an int
mysql_query("UPDATE Variable SET `upVote` = `upVote`+1 WHERE id= (variable here)) " //Making a row in my database w/ the id of the variable add 1 to the count
?>