jeffery_the_wind jeffery_the_wind - 1 year ago 171
Javascript Question

Receive .csv file as data in ajax success function

Please consider this javascript:


The URL returns a .csv file, but I am specifying the
data type because this is a cross-domain ajax request. Without that parameter I get the "origin is not allowed" error.

Since I specify the
data type, the ajax function throws an error because the .csv file is not JSON format. But in the dev console I can see that the browser DOES receive a coherent .csv file. So I know I am successfully receiving the CSV file. I think it should be possible, but I am not sure how to correctly receive this csv file to my ajax function??

Of course if I could make this URL return a correctly formatted JSON string that would be the best, but I am not sure I can do that.

Here is a fiddle where you can try it, you will have to open up the dev console to see that error:

Any help is greatly appreciated.


Answer Source

Unfortunately, cross-domain restrictions mean that this just isn't going to work. The system is built specifically so that you can't pull arbitrary cross-domain content with AJAX. There isn't any sort of pre-parse method to convert the non-JSONP data you're getting into actual JSONP data (because that would defeat the point of the restrictions).

You're going to have to either make a call to a local server that pulls the data from Yahoo! and sends it to your AJAX request, or find a service of some kind that will pull from an arbitrary URL and return the data as JSONP. As it happens, Yahoo! provides just such a service: YQL (Yahoo query language). See this link for more details.

To accomplish what you're wanting, use the code in this fiddle:

function get_url(remote_url) {
        url: ""+
        type: 'get',
        dataType: 'jsonp',
        success: function(data) {
        error: function(jqXHR, textStatus, errorThrow){
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download