Multiple file upload adds only one file - javascript

I am trying to reach multiple file/image upload with php, but what i get is only one file in my upload folder, form is sending by ajax. This is my code:
<input type='file' id='_file' multiple="multiple" name="SelectedFile[]">
<input type='button' id='_submit' value='Upload!'>
and PHP
<?php
// Output JSON
function outputJSON($msg, $status = 'error'){
header('Content-Type: application/json');
die(json_encode(array(
'data' => $msg,
'status' => $status
)));
}
$count = 0;
...
// Success!
foreach ($_FILES['SelectedFile']['name'] as $f => $name) {
outputJSON('File uploaded successfully to "' . 'upload/' . $_FILES['SelectedFile']['name'][0] . '".', 'success');
$count ++;
}
JS
var data = new FormData();
data.append('SelectedFile', _file.files[0]);
var request = new XMLHttpRequest();
request.onreadystatechange = function(){
if (request.readyState == 4){
try {
var resp = JSON.parse(request.response);
} catch (e){
var resp = {
status: 'error',
data: 'Unknown error occurred: [' + request.responseText + ']'
};
}
console.log(resp.status + ': ' + resp.data);
}
};
request.upload.addEventListener('progress', function(e){
_progress.style.width = Math.ceil(e.loaded/e.total) * 100 + '%';
}, false);
request.open('POST', 'upload.php');
request.send(data);
i still have Unknown error occurred: []

Remove the die call from the outputJSON function and use echo instead, it's terminating the script in the first loop of the foreach.
Update:
Assuming that the files are correctly uploaded and stored in $_FILES array, this code output should be parse-able by js:
header('Content-Type: application/json');
$output = array();
foreach ($_FILES['SelectedFile'] as $f => $file) {
$output []= array(
'data' => 'File uploaded successfully to "' . 'upload/' . $file['name'],
'status' => 'success',
);
}
echo json_encode($output);

Related

I keep getting this error in my code: Error: SyntaxError: Unexpected token 'o', "object(std"... is not valid JSON

Here is my php script for the registration page, the data is still being entered into the correct table but this problem is persistent.
Edit: I've seen comments asking for the javascript code, I've included it below the php code now.
`<?php
session_start();
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
main();
function main(){
require 'connectToDB.php';
// echo "\nreached the php file";
$response = array("code" => 0, "message" => "");
$request = file_get_contents('php://input');
$jsonRequest = json_decode($request);
var_dump($jsonRequest);
if (checkForExistingUser($conn, $jsonRequest) != 0){
$response["code"] = 2;
$response["message"] = "User already exists";
}
// else if($response["code"] == 1){
// // $userID = $conn->lastInsert();
// // header("Location: UniqueUserID.php");
// exit;
// }
else{
$response = addUser($conn, $jsonRequest);
// header("Location: UniqueUserID.php");
exit;
}
// printf(json_encode($response));
// var_dump($response);
$conn = null;
return json_encode($response);
}
function checkForExistingUser ($conn, $jsonRequest){
$stmt = $conn->prepare("
SELECT COUNT(Email) as noOfUsers
FROM user_main
WHERE Email = :confirmemailadd");
// $stmt -> bindParam(':confirmemailadd', $jsonRequest->confirmemailadd);
if (isset($jsonRequest->confirmemailadd)) {
$stmt->bindValue(':confirmemailadd', $jsonRequest->confirmemailadd);
} else {
$stmt->bindValue(':confirmemailadd', '');
}
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$results = $stmt->fetchAll();
$noOfResults = $results[0]["noOfUsers"];
// echo($noOfResults);
return $noOfResults;
}
function addUser($conn, $jsonRequest){
$response = array("code"=>0, "message"=>"");
// echo ("Reached addUser \n");
$firstname = sanitise($jsonRequest->firstname);
$surname = sanitise($jsonRequest->surname);
$username = sanitise($jsonRequest->username);
$confirmemailadd = sanitise($jsonRequest->confirmemailadd);
$phonenum = sanitise($jsonRequest->phonenum);
$retypepassword = sanitise($jsonRequest->retypepassword);
function encryptPassword($retypepassword) {
$key = openssl_random_pseudo_bytes(32);
$iv = openssl_random_pseudo_bytes(16);
$encrypted = openssl_encrypt($retypepassword, 'AES-256-CBC', $key, 0, $iv);
$hash = hash_hmac('sha256', $encrypted, $key);
return $hash . ':' . base64_encode($iv) . ':' . base64_encode($encrypted);
}
$stmt = $conn->prepare("
INSERT INTO user_main (Name, Surname, Username, Email, PhoneNum, PWD)
VALUES (:firstname, :surname, :username, :confirmemailadd, :phonenum, :retypepassword) ");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':surname', $surname);
$stmt->bindParam(':username', $username);
$stmt->bindParam(':confirmemailadd', $confirmemailadd);
$stmt->bindParam(':phonenum', $phonenum);
$stmt->bindParam(':retypepassword', $retypepassword);
try{
$stmt->execute();
$userID = $conn->lastInsertId();
$response["code"] = 1;
$response["message"] = "successfully added";
$response["user_id"] = $userID;
}
catch (PDOException $e){
$response["code"] = 0;
$response["message"] = $e->getMessage();
}
// echo json_encode($response);
return $response;
}
function sanitise($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
`
I'm still relatively new to the back-end development side of things but I cannot figure this one out, I've tried to google it and research other solutions on stack overflow but couldn't find anything useful
document.addEventListener('DOMContentLoaded', function () {
const form = document.querySelector('form');
form.addEventListener('submit', handleFormSubmit);
}, false)
function handleFormSubmit(event) {
event.preventDefault();
checkEmails();
checkPasses();
processForm();
// redirectToPage()
}
function checkEmails(){
var emailValue = document.getElementById("emailadd").value;
var retypeEmailValue = document.getElementById("confirmemailadd").value;
if (emailValue !== retypeEmailValue){
window.alert("Emails do not match.");
}
}
function checkPasses(){
var passValue = document.getElementById("password").value;
var retypeValue = document.getElementById("retypepassword").value;
if (passValue !== retypeValue){
window.alert("Passwords do not match.");
}
}
function processForm(){
var userDetails = gatherData()
console.log(userDetails);
postRequest(userDetails)
}
function gatherData(){
//gather the data from the form fields into JSON
var userDetails = {
firstname : document.getElementById("firstname").value,
surname : document.getElementById("surname").value,
username : document.getElementById("username").value,
confirmemailadd: document.getElementById("confirmemailadd").value,
phonenum: document.getElementById("phonenum").value,
retypepassword: document.getElementById("retypepassword").value,
}
return userDetails;
}
async function postRequest(userDetails){
// make an AJAX POST request to server
try{
const response = await fetch("../php/register.php",{
method: 'POST',
headers: {
'Origin' : 'http://localhost/',
'Content-Type': 'application/json', // sent request
'Accept': 'application/json' // expected data sent back
},
body: JSON.stringify(userDetails),
});
const data = await response.json();
console.log(data);
handleResponseCode(data);
}catch (error){
console.log('Error:',error);
}
}
function handleResponseCode(data){
console.log("response code: ", data.code);
console.log("response message: ", data.message);
if (data.code == 1){
alert ("Your account has been successfully created")
}
else if (data.code == 2 ){
alert (data.message );
}
}
You can try to catch the root cause of this error:
try {
$jsonResponse = json_encode($response);
} catch (Exception $e) {
// Handle JSON encoding error
die("JSON encoding error: " . $e->getMessage());
}
This will catch any exceptions thrown during the encoding process and allow you to handle them appropriately.
Edit:
function main(){
// ...
try {
$jsonResponse = json_encode($response);
} catch (Exception $e) {
// Handle JSON encoding error
die("JSON encoding error: " . $e->getMessage());
}
$conn = null;
return $jsonResponse;
}
you can put this catch error inside a function you wanna trace
Just remove the var_dump(...). Because that var_dump is already sending content back.

Progress Bar S3 Bucket - PHP Ajax, Javascript

I'm trying to add a Progress Bar to track the file Upload status of my Form. To upload files I use this Form code:
<form id="contact-form" action="awsUpload.php" method="post" name="frmImage" enctype="multipart/form-data">
<input class="file-input" type="file" style="width:100%;"autocomplete="off" name="ftp" accept="image/*, .zip, .rar, .bzip" onchange="this.form.submit();changeStyle()" class="file-up" id="fileFTP">
</form>
And this PHP code to manage the File Upload request.
<?php
require './aws/aws-autoloader.php';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
// AWS Info
$bucketName = '***';
$IAM_KEY = '***';
$IAM_SECRET = '***';
// Connect to AWS
try {
// You may need to change the region. It will say in the URL when the bucket is open
// and on creation. us-east-2 is Ohio, us-east-1 is North Virgina
$s3 = S3Client::factory(array(
'credentials' => array(
'key' => $IAM_KEY,
'secret' => $IAM_SECRET
),
'version' => 'latest',
'region' => 'eu-west-1'
));
}
catch (Exception $e) {
die("Error: " . $e->getMessage());
}
// For this, I would generate a unqiue random string for the key name. But you can do whatever.
//$target_file = 'f/' . basename($_FILES["ftp"]['tmp_name']); //ftp is file name at index.php
if (isset($_FILES["ftp"]) && $_FILES["ftp"]["error"] == 0) {
$mimeType = mime_content_type($_FILES["ftp"]["tmp_name"]);
$fileSize = $_FILES["ftp"]["size"];
if (strpos($mimeType, "image") === 0) {
if ($fileSize <= 1000 * 1024 * 1024) { //max image size
$target_dir = "i/";
// $strng = preg_replace("/[\s-]|\#/", "_", basename($_FILES["ftp"]["name"])); //Prima era solo "/[\s-]/"
$target_file = $target_dir . time() . rand(100, 999);
//$pathInS3 = 'https://s3.ap-south-1.amazonaws.com/' . $bucketName . '/' . $target_file;
// Add it to S3
try {
if (!file_exists('/tmp/tmpfile')) {
echo 3;
mkdir('/tmp/tmpfile');
}
$tempFilePath = '/tmp/tmpfile/' . basename($_FILES["ftp"]['name']);
$tempFile = fopen($tempFilePath, "w") or die("Error: Unable to open file.");
$fileContents = file_get_contents($_FILES["ftp"]['tmp_name']);
$tempFile = file_put_contents($tempFilePath, $fileContents);
$s3->putObject(array(
'Bucket' => $bucketName,
'Key' => $target_file,
'SourceFile' => $tempFilePath,
'StorageClass' => 'REDUCED_REDUNDANCY',
'ACL' => 'public-read'
));
$valPOutput = htmlspecialchars($target_file);
header('HTTP/1.1 303 See Other');
header('Location: http://example.com/result.php' . "?p=" . $valPOutput);
}
catch (S3Exception $e) {
die('Error:' . $e->getMessage());
}
catch (Exception $e) {
die('Error:' . $e->getMessage());
}
} else {
echo "image too big";
}
} elseif ($mimeType == "application/zip" || $mimeType == "application/x-rar-compressed" || $mimeType == "application/x-7z-compressed" || $mimeType == "application/x-bzip2") {
if ($fileSize <= 5000 * 1024 * 1024) { //max arch size
$target_dir = "f/";
//$strng = preg_replace("/[\s-]|\#/", "_", basename($_FILES["ftp"]["name"])); //Prima era solo "/[\s-]/"
$target_file = $target_dir . time() . rand(100, 999);
// $pathInS3 = 'https://s3.ap-south-1.amazonaws.com/' . $bucketName . '/' . $target_file;
// Add it to S3
try {
if (!file_exists('/tmp/tmpfile')) {
echo 3;
mkdir('/tmp/tmpfile');
}
$tempFilePath = '/tmp/tmpfile/' . basename($_FILES["ftp"]['name']);
$tempFile = fopen($tempFilePath, "w") or die("Error: Unable to open file.");
$fileContents = file_get_contents($_FILES["ftp"]['tmp_name']);
$tempFile = file_put_contents($tempFilePath, $fileContents);
$s3->putObject(array(
'Bucket' => $bucketName,
'Key' => $target_file,
'SourceFile' => $tempFilePath,
'StorageClass' => 'REDUCED_REDUNDANCY',
'ACL' => 'public-read'
));
$valPOutput = htmlspecialchars($target_file);
header('HTTP/1.1 303 See Other');
header('Location: http://example.com/result.php' . "?p=" . $valPOutput);
}
catch (S3Exception $e) {
die('Error:' . $e->getMessage());
}
catch (Exception $e) {
die('Error:' . $e->getMessage());
}
}else {
echo "arch too big";
}
}
}
?>
I've tried to do so adding event listeners to prevent submitting request, but when I upload a file, the website URL changes from https://example.com to https://example.com/awsUpload.php and the Progress Bar does not move and the Upload keeps going.
I'd like to receive some suggestions on how I can move or think to achieve that (the code I posted right now does not include any Progress bar test since I deleted the progress bar code cause it did not work).
EDIT DOWN HERE
Modified the form and added this new Script.
Right now the Load bar does work and the file gets uploaded, unfortunately I do not know why after the form gets submitted I do not get redirected to https://example.com/?p=****
<form id="contact-form" action="awsUpload.php" method="post" name="frmImage" enctype="multipart/form-data">
<input class="file-input" type="file" style="width:100%;"autocomplete="off" name="ftp" accept="image/*, .zip, .rar, .bzip" onchange="uploadFile(this.form)" class="file-up" id="fileFTP">
<progress id="upload-progress" value="0" max="100"></progress>
</form>
<script>
function uploadFile(form) {
var fileInput = form.querySelector('input[type="file"]');
var file = fileInput.files[0];
var formData = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open('POST', this.form, true);
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
var progressBar = form.querySelector('progress');
progressBar.value = percentComplete;
}
};
xhr.onload = function() {
if (xhr.status == 200) {
// File uploaded successfully
alert('success')
} else {
// An error occurred during the upload
}
};
xhr.send(formData);
}
</script>
Extra: I tried to ad in the action of if (xhr.status == 200) to redirect to a certain webpage with window.location but I'm missing the $valPOutput from the awsUpload.php and do not know how to get it.

Slim 3 returns array(0) for getUploadedFiles() when trying to perform POST request from web page

I am trying to perform a Post request to store some dummy data to my database. The data set consist of three text fields and a file.
Following the Slim 3 File Upload Documentation I created my service which works perfectly.
Here's my service code:
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use Slim\Http\UploadedFile;
$container = $app->getContainer();
$container['upload_directory'] = __DIR__ . '/uploads/';
$app->post('/np/register',function(Request $request, Response $response){
$np_name = $request->getParam('np_name');
$np_language = $request->getParam('np_language');
$uploadedFiles = $request->getUploadedFiles();
$upload_folder = '/uploads/';
$directory = $this->get('upload_directory');
$np_image_path = $uploadedFiles['np_image_path'];
$np_active_status = $request->getParam('np_active_status');
$register_date = date('Y/m/d H:i:s');
//Getting the server ip
$server_ip = gethostbyname(gethostname());
try
{
$np_name_check = preg_match('~^[A-Za-z ]{3,20}$~i', $np_name);
$np_language_check = preg_match('~^[A-Za-z_]{3,20}$~i', $np_language);
$np_active_status_check = preg_match('/^[0-1]{1}$/', $np_active_status);
if($np_name_check>0 && $np_language_check>0 && $np_active_status_check>0 && isset($np_name) && isset($np_language) &&
isset($np_active_status) && isset($np_image_path))
{
$get_filename = moveUploadedFile($directory, $np_image_path);
$ServerURL = 'http://'.$server_ip.'/np_console/src/routes'.$upload_folder.$get_filename;
$np_image_path = $ServerURL;
$sql = "INSERT INTO np_registration (np_name,np_language,np_image_path,np_active_status,np_register_date) VALUES (:np_name,:np_language,:np_image_path,:np_active_status,:register_date)";
try
{
//Get DB Object
$db = new db();
//Connect to database
$db = $db->connect();
$stmt = $db->prepare($sql);
$stmt->bindParam(':np_name', $np_name);
$stmt->bindParam(':np_language', $np_language);
$stmt->bindParam(':np_image_path', $np_image_path);
$stmt->bindParam(':np_active_status', $np_active_status);
$stmt->bindParam(':register_date', $register_date);
$stmt->execute();
echo '{"notice":{"respnse":"NetPicks Added Successfully"}';
}
catch(PDOException $e)
{
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
else{
echo '{"error":{"respnse":"\nInvalid Data Entry"}';
}
}
catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
});
function moveUploadedFile($directory, UploadedFile $uploadedFile)
{
$extension = pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION);
$basename = bin2hex(random_bytes(8));
$filename = sprintf('%s.%0.8s', $basename, $extension);
$uploadedFile->moveTo($directory . DIRECTORY_SEPARATOR . $filename);
return $filename;
}
?>
My Post request via Postman works as required and I am able to insert values to my db.
Postman Response
But when I try to perform the POST request from my web page it fails. On using the var_dump I found out that $uploadedFiles always returns array(0).
Post Service call:
export default function NP_Registration_Service(type, np_name, np_language, np_image_path, np_active_status){
let BaseUrl = 'http://localhost/np_console/public/index.php';
let formData = new FormData();
formData.append('np_name', np_name);
formData.append('np_language', np_language);
formData.append('np_image_path', np_image_path);
formData.append('np_active_status', np_active_status);
return new Promise((resolve,reject) => {
fetch(BaseUrl+type,{
method: 'POST',
body: formData
})
.then((response) => {
var resText = response.text();
console.log("The resText");
console.log(resText);
})
.catch((error) => {
reject(error);
});
});
}
Here's the response with var_dump($uploadedFiles) which returns array(0).
Console Output
I have looked into this but it didn't provide any help.
So am I making a mistake with the service call?
As suggested by Karol Samborski adding
var fileField = document.querySelector("input[type='file']");
formData.append('np_image_path', fileField.files[0]);
to the Post service call(fetch request) resolved the issue.

How to save data which is inside a table dynamically created using JavaScript to database

function create(x) {
var field=document.createElement('fieldset');
var t=document.createElement('table');
t.setAttribute("id","myTable");
document.body.appendChild(t);
field.appendChild(t);
document.body.appendChild(field);
var row=document.createElement('th');
newHeader = document.createElement("th");
newHeader.innerText = x;
row.appendChild(newHeader);
var row1=document.createElement('tr');
var col1=document.createElement('td');
var col2=document.createElement('td');
var row2=document.createElement('tr');
var col3=document.createElement('td');
var col4=document.createElement('td');
var row3=document.createElement('tr');
var col5=document.createElement('td');
var col6=document.createElement('td');
col1.innerHTML="Name";
col2.innerHTML="<input type='text' name='stateactivityname' size='40' required>";
row1.appendChild(col1);
row1.appendChild(col2);
col3.innerHTML="Registration Applicable";
col4.innerHTML="<select name='regapp' required><option></option><option>Yes</option><option>No</option></select>";
row2.appendChild(col3);
row2.appendChild(col4);
col5.innerHTML="Registers Applicable";
col6.innerHTML="<select name='registers' required><option></option><option>Yes</option><option>No</option></select>";
row3.appendChild(col5);
row3.appendChild(col6);
t.appendChild(row);
t.appendChild(row1);
t.appendChild(row2);
t.appendChild(row3);
addrow('myTable');
}
PHP code for storing data to database is:
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
$conn=new mysqli("localhost","root","","newcomplyindia");
if($conn->connect_errno){
echo("connection error");
}
$actname=$_POST["actname"];
$industry=$_POST['industrytype'];
$centralorstate=$_POST["cors"];
$sql="insert into acts (actname,centralorstate) value ('".$actname."','".$centralorstate."')";
$regapp=$_POST["regapp"];
if($regapp=='Yes'){
$regapp=true;
}
else{
$regapp=false;
}
$registers=$_POST["registers"];
if($registers=='Yes'){
$registers=true;
}
else{
$registers=false;
}
$sub=$_POST["sub"];
if($sub=='Yes'){
$sub=true;
}
else{
$sub=false;
}
if($conn->query($sql)==true){
echo 'act name added ';
}
$lastid=$conn->insert_id;
$sql1="insert into actsstate (actid,registrationrequired,registersapplicable,sublocation)"
. "values('$lastid','$regapp','$registers','$sub')";
if($conn->query($sql1)==true){
echo '<br>name and central/state added';
}
$stateactivity=$_POST["stateactivityname"];
$activityname=$_POST["activityname"];
$activitymonth=$_POST["month"];
$activitydate=$_POST["date"];
$sql2="insert into activity (name,actid,activityname,activitymonth,activitydate)"
. "values('$stateactivity','$lastid','$activityname','$activitymonth','$activitydate')";
if($conn->query($sql2)){
echo 'activity added';
}
else{
echo 'no record';
}
$conn->close();
?>
i have a javascript like this. The table is created dynamically. And i want to store the data inside this table to database. am using mysqli for database connection
Am new to javascript. Can anyone help me to do this
Here's a way using Vanilla JS (pure js)
var xhttp = new XMLHttpRequest();
var url = "save.php";
xhttp.open("POST", url, true);
// uncomment this if you're sending JSON
// xhttp.setRequestHeader("Content-type", "application/json");
xhttp.onreadystatechange = function() { // Call a function when the state changes.
if(xhttp.readyState == 4 && xhttp.status == 200) {
// the 4 & 200 are the responses that you will get when the call is successful
alert(xhttp.responseText);
}
}
xhttp.send('the data you want to send');
And here's a way to save to the database (mysql in my case) with Flat PHP (pure php)
$servername = "localhost";
$username = "db_username";
$password = "db_password";
$dbname = "db_name";
// connect to the DB
$conn = new mysqli($servername, $username, $password, $dbname);
// check if you're connected
if ($conn->connect_error) {
echo "Connection failed: " . $conn->connect_error;
}
else {
// echo "connecting to DB succeeded <br> ";
}
// uncomment the following if you're recieving json
// header("Content-Type: application/json");
// $array = json_decode(file_get_contents("php://input"), true);
$sql = "INSERT INTO table_name (columns,names) VALUES (columns,values)";
if ($conn->query($sql) === TRUE) {
echo "Data was saved successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
to learn more about the sql commands I suggest the w3schools tutorials
Of course you can by using AJAX:
$.post("php_script.php",{javascript variables}, function(result) {
alert(result);
});

Using PHP to retrieve a PDF (with JSON)

I'm using JS and PHP to collect a rows of information from a MySQL DB. This is working fine until I'm adding code to get a PDF-blob in the same return.
var docs;
getMini = function() {
showMiniLoading();
var req = new XMLHttpRequest();
req.onload = function() {
console.log("GOT IT!");
var temp = JSON.parse(this.responseText);
docs = temp;
hideMiniLoading();
printAllMini();
};
req.open("get", "resources/php/newMini.php", true);
req.send();
console.log("SENT!");
}
showPDF = function(id) {
for (var i = 0; i < docs.length; i++) {
var object = docs[i];
if (object.id == id) {
console.log("Found it! :D " + i);
console.log("Content: " + object.pdf);
// MORE STUFF HERE
document.getElementById("pdf").innerHTML = '<object "data:application/pdf,' + object.pdf + '" type="application/pdf" width="100%" height="100%"> <p>Alternative text - include a link to the PDF!</p> </object>';
break;
}
}
}
<?php
session_start();
include_once 'maindb.php';
$mysqli = mysqli_connect($dbMain['host'], $dbMain['user'], $dbMain['pass'],
$dbMain['db'])
or die('Kunde inte ansluta till databasen:'.mysqli_error($Maincon));
if(!$result = $mysqli->query(
"SELECT tblDokument.ID, tblMail.inkommet,
tblDokument.datum, tblDokument.Moms, tblDokument.pris, tblDokument.Org,
tblVerifikat.verifikatNo, tblLevMallar.OrgNr, tblLevMallar.name,
tblDokumentSvg.svg, tblDokumentPdf.pdf
FROM tblDokument
LEFT OUTER JOIN tblVerifikat ON tblDokument.ID = tblVerifikat.ID
LEFT OUTER JOIN tblMail ON tblDokument.tblMail_ID = tblMail.ID
LEFT OUTER JOIN tblLevMallar ON tblDokument.orgnr = tblLevMallar.OrgNr
LEFT OUTER JOIN tblDokumentSvg ON tblDokument.ID = tblDokumentSvg.dokumentid
LEFT OUTER JOIN tblDokumentPdf ON tblDokument.ID = tblDokumentPdf.id
WHERE tblVerifikat.verifikatNo <> 'Makulerad'
ORDER BY tblDokument.ID"))
{
echo "VERYTHING IS BAD";
}
else {
$i = 0;
while ($row = $result->fetch_assoc()) {
$tempPDF = $row["pdf"];
$size = filesize($tempPDF);
header('Content-type: application/pdf');
header("Content-length: $size");
header('Content-Disposition: attachment; filename="new.pdf")');
$tempArray[$i] = array(
"id" => $row["ID"],
"arrived" => substr($row["inkommet"], 0, 10),
"booked" => $row["datum"],
"verification" => $row["verifikatNo"],
"org" => $row["name"],
"price" => $row["pris"],
"stax" => $row["Moms"],
"pic" => base64_encode($row["svg"]),
"pdf" => $tempPDF);
$i++;
}
// HEADER STUFF
$done = json_encode($tempArray);
$size = strlen($done);
header('Content-type: application/json');
header("Content-length: $size");
header('Connection: close');
echo $done;
}
$result->close();
$mysqli->close();
?>
I encode the result with JSON at the end, but whatever I do I end up with a column full of null-values, instead of the desired PDF-blob. I've also tried to encode the entire pdf with base64_encode(), but then I get an error that says:
Uncaught SyntaxError: Unexpected token <
.. in the console of my browser.
Actual question:
How do i send a PDF-blob together with some other information and encoded in JSON?
I've tried a lot of other threads but haven't seen a solution that works in this case :/
NOTE:
I am very now to PHP and any additional feedback about the efficiency of the code above is highly appreciated.

Categories

Resources