javascriptphphtmlinput-type-file

How to not make inputType-file send data to another php file?


I am trying to build a page that would just do three things:

So far I have acquired some code-snippets to use in some parts of my code:

To access the php variable (containing contents) in JS :

<?php
$somevar = 'Hi Thunkable!';
?>

<script>
var msg = <?php echo $somevar; ?>;
.... process the variable further
</script>

Input-type: file form for the upload button as I have the JS code in the current file, how do I make the form NOT send data to another php file?

<form enctype="multipart/form-data" action="__URL__" method="POST">
    Send this file: <input name="userfile" type="file" />
    <input type="submit" value="Send File" />
</form>

The only part remains for me is as I said above, instead of sending the uploaded file data to another PHP file, store it in a variable. I found out that $txt = file_get_contents($_FILES['userfile']['tmp_name']); could get the contents from a file.

Summing up, I am just trying to keep all my code in one HTML file, which includes uploading the file, reading it's contents and storing in a var., and processing the contents further. Is something like this possible to do? I am a beginner in PHP/HTML/JS so I couldn't think of anything to search beforehand regarding my question...


Solution

  • You can use object FileReader for read files from the input type file

    here is the example:

    (function(){
        
        function onChange(event) {
            var reader = new FileReader();
            reader.onload = (event)=>{
              alert(event.target.result);
              let data = JSON.parse(event.target.result);
              //process the data here
              console.log(data);
            }
            reader.readAsText(event.target.files[0]);
        }
     
        document.getElementById('file').addEventListener('change', onChange);
    
    }());
    <input id="file" type="file" accept="application/JSON" />