netrunner
netrunner

Reputation: 11

Detect/find *.pdf on server (with php?) and pass it to .js file

I'm completely new to javascript. I have a .js (running on webserver) file with two options:


defaultUrl: {
    value: "filename.pdf",
    kind: OptionKind.VIEWER
  }, 

and instead of filaname.pdf name I would like it to detect any .pdf file in current working folder (there will always be one, but each time with different filename) and return it's name here

The file is on shared web hosting - so I probably can run some .php code to find the filename

edit:

// If absolute URL from the remote server is provided, configure the CORS
// header on that server.
var url = 'https://raw.githubusercontent.com/mozilla/pdf.js/ba2edeae/examples/learning/helloworld.pdf';

// Loaded via <script> tag, create shortcut to access PDF.js exports.
var pdfjsLib = window['pdfjs-dist/build/pdf'];

// The workerSrc property shall be specified.
pdfjsLib.GlobalWorkerOptions.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.js';

// Asynchronous download of PDF
var loadingTask = pdfjsLib.getDocument(url);
loadingTask.promise.then(function(pdf) {
  console.log('PDF loaded');

Upvotes: 0

Views: 305

Answers (1)

digijay
digijay

Reputation: 1366

Assume you have this directory structure:

$ tree test
test
├── test-find-pdf.php
└── test.pdf

0 directories, 2 files

Then you can get all pdf files in the current working directory using glob(). To return the name of the first pdf file found modify your php script like this:

<?php
    # file test-find-pdf.php

    $allPdfFiles = glob("*.pdf");
    echo $allPdfFiles[0];
?>

That way you can call it from your javascript with an XMLHttpRequest (aka Ajax request) like this:

<script>
var request = new XMLHttpRequest();
request.open("GET","test-find-pdf.php");
request.addEventListener('load', function(event) {
   if (request.status >= 200 && request.status < 300) {
      console.log(request.responseText);
   } else {
      console.warn(request.statusText, request.responseText);
   }
});
request.send();
</script>

So on load of your html document the Ajax returns the result of the php file and prints it to the console F12 in your browser. From there you have to find a way to assign it to your json object.

Make sure that the path to your php file in request.open() is correct.

Further information on glob() can be found in the php manual.

Upvotes: 1

Related Questions