Search code examples
javascriptjqueryajaxcsvxmlhttprequest

How to get a CSV file from an external URL using Javascript


I am trying to get a CSV file from the following URL (http://s3.amazonaws.com/misc-ww/data.csv) and parse the data in this file on the fly. What I am trying to achieve by parsing the data in the file is important, feel free to look at the file if you wish to make suggestions on it; however my current problem lies in getting the data in the file itself. When using either XMLHttpRequest, or an Ajax call, or a JSONP call; the response is always returning with error. Meaning that the file for some reason cannot be accessed.

After researching for a few hours, I am sure this has got to do with some kind of security restriction (cross domain request), sadly I have not come any closer to understanding how to get around it. For sample purposes I have created a jsFiddle highlighting my attempt at retrieving the CSV file via an AJAX JSONP call (code seen below).

HTML

<button>Click me to get the CSV File</button>

Javascript

function getCSV() {
    $.ajax({
        url: "http://s3.amazonaws.com/misc-ww/data.csv",
        type: 'get',
        dataType: 'jsonp',
        success: function(data) {
            alert("Success: " + data);
        },
        error: function(jqXHR, textStatus, errorThrow){
            alert("Error: " + jqXHR['responseText']);
        }
    });
}

$('button').click(function() { getCSV(); });

My main goal is to be able to achieve this via Javascript alone, however I do welcome any answers that involve jQuery. I am aware of javascript frameworks that could allow this to work for me, but in my case I need to code without them.


Solution

  • You cant really bypass CORS with JSONP calls if server doesn't support them. Its more the way server don't have to set "Access-Control-Allow-Origin: *" header. Instead server can send respond inside callback function to bypass straight JSON response. So your problem is that you .csv file is not wrapped inside a callback function.

    So server which supports JSONP and gets ?callback=cbFunc it will print:

    cbFunc('here is my file content')
    

    Now you are asking .csv file and server is sending it without wrapping it to callback function. That's why you end up with security restriction.

    Long story short: You cant get file via AJAX JSONP like that because s3.amazonaws.com does not support JSONP.

    here is nice explanation about JSON and JSONP: http://json-jsonp-tutorial.craic.com/index.html

    Sorry about repeating myself.