-1

I want to get and read a JSON file that would be uploaded by the user.

I created the html input file:

<div id="button_open" class="button">
    <span>Open a JSON file</span>
    <input id="input_open" class="input_file" type="file">
</div>

And now, I don't know how to load the data from the file. I only can get the filename.

Here is what I wrote:

$(document).ready(function(){
    $("#input_open").change(onOpenChange);
})

function onOpenChange(e) {
    var filname = $("#input_open").val();
    var fileContent = ... ?
    var jsonData = JSON.parse(fileContent);
}

Anyone knows how to get the file content?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
superrache
  • 650
  • 11
  • 26
  • Have a read: [Using files from web applications](https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications) – emerson.marini Dec 19 '14 at 10:26

2 Answers2

4
    <script>
 $(document).ready(function(){
        $("#input_open").change(onOpenChange);
    })

    function onOpenChange(e) {
        var filname = $("#input_open").val();
        var fileContent = getTxt();
        var jsonData = JSON.parse(fileContent);
    }
    getTxt = function (){

      $.ajax({
      url:'text.json',
      success: function (data){
          fileContent =data;           
          return data 
      }
      });
    }
    </script>
-3

Here is the solution I get with the help of Ameen:

    $(document).ready(function(){

    $("#input_open").change(onOpenChange);

})

function onOpenChange() {
    var filePath = $("#input_open").val();
    var startIndex = filePath.indexOf('\\') >= 0 ? filePath.lastIndexOf('\\') : filePath.lastIndexOf('/');
    var filename = filePath.substring(startIndex);
    if(filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
        filename = filename.substring(1);
    }

    $.ajax({
        url: filename,
        success: onOpenLoad
    });
}

function onOpenLoad(fileContent) {
    var data = JSON.parse(fileContent);
    // do something with the data
}
superrache
  • 650
  • 11
  • 26
  • 1
    I don't get it, you got the guy's answer, changed it to fit your exact code (his answer was working as a general idea, he couldn't foresee what your exact code or filenames looked like) and then selected your own answer as the correct one? – Luca Bezerra Mar 06 '20 at 16:44