1

I have almost zero experience with Javascript , I need to use this Javascript in my php script .

<script>

let arr = ["alfa", "beta", "charlie"]

const updateResult = query => {
    let resultList = document.querySelector(".result");
    resultList.innerHTML = "";

    arr.map(algo =>{
        query.split(" ").map(word =>{
            if(algo.toLowerCase().indexOf(word.toLowerCase()) != -1){
                resultList.innerHTML += `<li class="list-group-item">${algo}</li>`;
            }
        })
    })
}

updateResult("")
</script>

This script load the data using

let arr =

However suppose I have all the data specified there in a file in this format

c:/data/mydata.txt

and the data.txt contains data in this form (one data per row)

alfa
bravo 
charlie

Now how should I change the javascript above to load the data from c:/data/mydata.txt and not using

let arr = ["alfa", "beta", "charlie"] 

?

Thank you

gr68
  • 420
  • 1
  • 10
  • 25
  • 2
    You can't access the servers nor the clients file system using javascript. – Jonas Wilms Dec 24 '18 at 10:20
  • 2
    Javascript can not access the client file system by itself due to security reasons. If you want something like this you will need to let the user upload the file using a file input. – Mark Baijens Dec 24 '18 at 10:20
  • 1
    Check [this](https://stackoverflow.com/questions/14446447/how-to-read-a-local-text-file). – holydragon Dec 24 '18 at 10:21
  • Javascript in the browser cannot access arbitrary files on the disk. This is by design as it would open a huge security hole – derpirscher Dec 24 '18 at 10:21
  • I have this data available in php , how can I send this data to Javascript script above ? – gr68 Dec 24 '18 at 10:24
  • Thank you holydrangon , can you tell me how to modify my script using readTextFile("file:///C:/your/path/to/file.txt"); ? – gr68 Dec 24 '18 at 10:26
  • If you have your data available in PHP you can either: 1) insert the data when you initially deliver the page or 2) load the data with a separate ajaxcall – derpirscher Dec 24 '18 at 10:41

2 Answers2

1

You do not need to change your file, but you cannot use it directly due to security issues. If I would write a Javascript which reads your secret files and you load my page, all your secrets would be revealed, therefore, if you want to load a file, you either have to allow your user to upload it and once the user uploads the file do your logic, or, you can request it via AJAX.

How to upload a file

An example for this is

<!DOCTYPE html>
<html>
<body onload="myFunction()">

<input type="file" id="myFile" multiple size="50" onchange="myFunction()">

<p id="demo"></p>

<script>
function myFunction(){
  var x = document.getElementById("myFile");
  var txt = "";
  if ('files' in x) {
    if (x.files.length == 0) {
      txt = "Select one or more files.";
    } else {
      for (var i = 0; i < x.files.length; i++) {
        txt += "<br><strong>" + (i+1) + ". file</strong><br>";
        var file = x.files[i];
        if ('name' in file) {
          txt += "name: " + file.name + "<br>";
        }
        if ('size' in file) {
          txt += "size: " + file.size + " bytes <br>";
        }
      }
    }
  } 
  else {
    if (x.value == "") {
      txt += "Select one or more files.";
    } else {
      txt += "The files property is not supported by your browser!";
      txt  += "<br>The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead. 
    }
  }
  document.getElementById("demo").innerHTML = txt;
}
</script>

<p><strong>Tip:</strong> Use the Control or the Shift key to select multiple files.</p>

</body>
</html>

source: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_fileupload_files

Getting the file via AJAX

In order to do that, you will need to:

  • send an AJAX request in your javascript code
  • parse the request and send back the file via PHP
  • do your logic in Javascript when the request is responded

Example:

HTML

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Download POST Request</title>
</head>
<body>
Enter a text and click the button: <input type="text" id="content" value="Text for the generated pdf">
<button id="download">Send AJAX Request and download file</button>

<script>
  document.getElementById('download').addEventListener('click', function () {
    var content = document.getElementById('content').value;
    var request = new XMLHttpRequest();
    request.open('POST', '../server/', true);
    request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    request.responseType = 'blob';

    request.onload = function() {
      // Only handle status code 200
      if(request.status === 200) {
        // Try to find out the filename from the content disposition `filename` value
        var disposition = request.getResponseHeader('content-disposition');
        var matches = /"([^"]*)"/.exec(disposition);
        var filename = (matches != null && matches[1] ? matches[1] : 'file.pdf');

        // The actual download
        var blob = new Blob([request.response], { type: 'application/pdf' });
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = filename;

        document.body.appendChild(link);

        link.click();

        document.body.removeChild(link);
      }

      // some error handling should be done here...
    };

    request.send('content=' + content);
  });
</script>
</body>
</html>

PHP

<?php
require_once 'vendor/autoload.php';

if($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-type: application/pdf');
    http_response_code(200);

    // Contents
    $pdfContent = !empty($_POST['content']) ? $_POST['content'] : 'no content specified';

    // Generate the PDOF
    $pdf = new FPDF();
    $pdf->AddPage();
    $pdf->SetFont('Arial','B',16);
    $pdf->Cell(40,10, $pdfContent);

    return $pdf->Output(null, 'foobar-' . time() . '.pdf');
}

// Bad method
http_response_code(405);
exit();

Source: https://nehalist.io/downloading-files-from-post-requests/

You will of course need to modify the code to comply to your needs. Reading a tutorial would not hurt.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
0

you can use ajax for loading data from external file. a sample of jquery get call is given below. You can also use the same code with your file path and variables.

    $("button").click(function(){
  $.get("demo_test.php", function(data, status){
    alert("Data: " + data + "\nStatus: " + status);
  });
});

if you are using pure java script instead of jQuery you have to use pure ajax calls.

for more details about jQuery ajax check this link

VISHNU
  • 948
  • 8
  • 15
  • Thank you , could you tell me how to modify my file, I'm really lost. – gr68 Dec 24 '18 at 10:30
  • you need to read data from a php file in the browser , am I correct? $.get("localhost/filename...", function(data, status){ console.log(data) }); in the data you will get what you "echo" or "print" from the php file so you can use the data to loop and do your work – VISHNU Dec 24 '18 at 10:35
  • @VISHNURadhakrishnan the question was not tagged jQuery and your solution will only work if the asker is using jQuery. – Lajos Arpad Dec 24 '18 at 11:12