Using d3 or ajax to read a local file containing tab-separated values may result in a syntax error appearing in the Firefox development console

The reading operation is functioning as expected. However, I encountered a syntax error in the Firefox console while going through multiple files, which can be quite tedious. These files are annotation files formatted like (time \t value) with no headers, for example:

0.0   5.2
0.5   5.6
1.0   6.3
...

Below is the AJAX code snippet being used:

function getdatafromfile(filename)  {
// Read annotation file. Example : %timeinstant \t %value \n
// Return an array of string
var arraydata;
 $.ajax({
      type: "GET",
      url: filename,
      dataType: "text",
      async: false,
      success: function(csv) {arraydata = $.csv.toArrays(csv,{separator:'\t'}); }
      });

   return arraydata;
}

Using D3:

d3.text(filename, function(text) {

        var data = d3.tsv.parseRows(text).map(function(row) {
            return row.map(function(value) {
                return +value;
                });
            });
        console.log(data);
    });
}

It appears that one of these codes should work, but unfortunately, I am encountering a syntax error in both cases (using Firefox 33.1).

Answer №1

The functionality of a file reader can be demonstrated with the code snippet provided below.

In this sample, a flag has been included to allow the use of variable content instead of an actual file. This feature is primarily for demonstration purposes and can be removed as needed. The same code can also be accessed on jsFiddle.

It is advisable to incorporate validation checks before or after utilizing the $.csv method to ensure that the file being processed is indeed a csv/tsv file.

If there is a requirement to open a file without user interaction, alternative methods need to be explored due to security restrictions in JavaScript preventing direct file access without user consent (refer to this SO question).

One possible approach could involve storing the data in a database such as Firebase or MongoDB, or using a JSON file. The code from my previous response should function properly when working with a hosted JSON file within your webpage.

var demoTxt = "0.0   5.2\
0.5   5.6\
1.0   6.3";

var flag_usedemofile = true; //if true var demoTxt will be used

function doOpen(evt) {
  var files = evt.target.files,
      reader = new FileReader();
    reader.onload = function() {
        if ( !flag_usedemofile) {
            var arraydata = $.csv.toArrays(this.result,{separator:'   '});
            showout.value = arraydata; //this.result;
        } else {
            var arraydata = $.csv.toArrays(demoTxt,{separator:'   '});
            showout.value = arraydata;
            console.log(arraydata);
        }
    };
    reader.readAsText(files[0]);
}
    
var openbtn = document.getElementById("openselect"),
    showout = document.getElementById("showresult");
openbtn.addEventListener("change", doOpen, false);
#showresult {
  width:98%;
  height: 300px;    
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>
<input type="file" id="openselect" />
<textarea id="showresult"></textarea>

Answer №2

It's a bit unclear what specific syntax error you're encountering. It seems like the issue might be related to the mime type of your json request.

A possible solution could be to encapsulate your data in JSON format and then utilize JSONP. (I attempted using text/plain, but unfortunately, it didn't work.)

Please refer to the example below for more information. You can also access the same demonstration on jsFiddle.

(function ($) {
    var url = 'http://www.mocky.io/v2/547c5e31501c337b019a63b0'; // dummy url

    var jsonCallback = function (csv) {
        var arraydata;
        console.log(data);
        $('#data').html(JSON.stringify(csv, null, 2));
        arraydata = $.csv.toArrays(csv.data,{separator:'\t'});
        console.log(arraydata); 
    };

    $.ajax({
        type: 'GET',
        url: url,
        contentType: "application/json",
        dataType: 'jsonp'
    }).done(jsonCallback)
    .fail(function (xhr) {
        alert("error" + xhr.responseText);
    });

})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id='data'></pre>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are the steps to create a dynamic navigation bar in React without encountering hydration issues?

My goal is to dynamically show or hide links based on user authorization. Here's my initial approach: const Navbar = () => { const { canDo, ...} = useUser(); //A Zustand store return ( <> <div> <ul> ...

How to remove a loop-rendered component from the DOM in Vue

My website has an image upload form where users can select multiple images. Once the images are selected, they are previewed and users can provide meta info such as Category and Type for each image. This functionality is implemented in the upload.vue file ...

Find the flowplayer when the page loads

Is there a way to make a flowplayer seek at the page load without it resetting? I've tried this: $(document).ready(function() { $f(0).seek(5); }); also tried: $(document).ready(function() { while(!$f(0).isLoaded()) { $f(0).seek(5); } }); ...

What is the solution for the error "does not exist on type 'HTMLTableDataCellElement'" in Angular?

When working on my Angular project, I implemented a PrimeNG p-table component. <p-table [value]="users" class="user-roles-table" [rows]="5" [showCurrentPageReport]="true" [ ...

Getting data in a ng-Dialog Modal with AngularJS is a breeze!

Hi there, I'm new to Angular JS and facing an issue with displaying data from my MySQL database in a table as well as in a modal for more detailed information: I've included the HTML file named _detail_modal.html at the bottom of the page. ...

What is the best way to display data in the User Interface when data is being received through the console in AngularJS?

I have created an HTML file and the corresponding controller logic for this page. I can see the data in the console, but it's not displaying on my UI. <div id="panelDemo14" class="panel panel-default" ng-controller="NoticeController"> < ...

Output various strings to the standard output and stream them individually

Is there a way to redirect each string output to standard out to another command? // Example file: example.js #!/usr/bin/env node process.stdout.write('foo') process.stdout.write('bar') After running ./example.js | wc -m, the total ch ...

Creating a window.variable in a jQuery ajax callback using CoffeeScript

This particular project is built using rails and backbone-on-rails framework. Despite my efforts, I have been facing an issue with setting a global variable in a response callback function. Here's what I have attempted so far: 1) Initialization of t ...

Assistance with designing in JavaScript and Python

Currently, I have a setup where my external website is extracting data from an iframe within our internal company intranet using Javascript. The extraction process is successful, but now I am faced with the challenge of accessing this harvested data in ord ...

Run the Ionic function only when the app is launched for the first time

I'm facing an issue with a function in Ionic storage that sets an array to default values. I only want this function to run the first time the app is launched on a user's phone, but currently it runs every time the app is opened because it's ...

How can a JSON string be assigned to a variable for use in a Google pie chart?

I am currently experiencing an issue with my web server. I am sending a JSON object as an argument via render_template to my website, where I intend to use this data to display a Google pie chart. The problem arises when I try to assign the Google pie cha ...

In a particular configuration involving Docker and Nginx rewrite rules, there is a notable alteration in URLs that include question marks when utilized in jQuery.ajax calls

My PHP/Laravel app is running smoothly in a dockerized environment using the php:7.4-apache container. During development, we had it accessible through http://localhost:81. Now, our aim is to make this service available at http://localhost/foo/bar within ...

Chosen option within the AntD Select component

Using the AntD select component, there seems to be an issue where it displays "id" instead of "name" when selecting options. Is there a solution available for this problem? const MyComponent = () => { const data = [ { id: "5c83c2d ...

Error: The XML parsing in ASP failed to find a root element at the specified location

When clicking the button, I have jQuery/Ajax code that is supposed to pass the value of a selected radio button to a controller action and open a detail page. However, I am encountering an error. When using Mozilla Firefox, the console displays: XML Par ...

PHP Timer for Keeping Track of Time

Is it feasible to develop a timer using PHP that triggers an action after 60 seconds? I am looking for a countdown effect where the timer starts at 60 and decreases to 0. Ideally, I would like to refresh the corresponding div element to simulate the countd ...

What is the best way to assign a unique number to every div id that is generated?

I am currently using a django for loop to retrieve data from a query set. As the information is displayed, I would like to have each item wrapped in a div tag with a unique id that increments by 1 for every instance. Is there a way to achieve this directly ...

How to incorporate both image and text links within an HTML div container using JavaScript

I am trying to create a clickable image and text within a div named "films" that both link to the same webpage. However, I am experiencing an issue where only the text link works and the image link is disabled. If I remove the text link, then the image l ...

Can Python's datetime object be used interchangeably with a JavaScript date object?

Take for instance in python, a date might look like: 2020-06-19T11:32:16.548109Z, is there a method I can utilize to transform this into a javascript Date object? ...

What is the process for loading JavaScript along with its dependencies?

Imagine a scenario where I have script A that loads another script B: $.getScript('B.js', foo); Now, what if script B also loads an additional script? In that case, I want the function foo to be executed only after both B and its loaded script ...

Guide on utilizing jQuery/AJAX data with PassportJS

When I submit a login request using the form fields action="/login", method="post", everything works smoothly. This is similar to the code examples found either here or here. However, when I attempt to send the same information using jquery/ajax, passport ...