Receive .csv file as data in ajax success function

17,801

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: http://jsfiddle.net/c5TeM/1/

function get_url(remote_url) {
    $.ajax({
        url: "http://query.yahooapis.com/v1/public/yql?"+
"q=select%20*%20from%20html%20where%20url%3D%22"+
encodeURIComponent(remote_url)+
"%22&format=json",
        type: 'get',
        dataType: 'jsonp',
        success: function(data) {
            alert(data.query.results.body.p);
        },
        error: function(jqXHR, textStatus, errorThrow){
            alert(jqXHR['responseText']);
        }
    })
}
Share:
17,801
jeffery_the_wind
Author by

jeffery_the_wind

Currently a Doctoral student in the Dept. of Math and Stats at Université de Montréal. In the past I have done a lot of full stack development and applied math. Now trying to focus more on the pure math side of things and theory. Always get a lot of help from the Stack Exchange Community! Math interests include optimization and Algebra although in practice I do a lot of machine learning.

Updated on June 24, 2022

Comments

  • jeffery_the_wind
    jeffery_the_wind almost 2 years

    Please consider this javascript:

    $.ajax({
        url:'http://ichart.finance.yahoo.com/table.csv?s=GS&a=00&b=1&c=2010&d=08&e=3&f=2012&g=d&ignore=.csv',
        type:'get',
        dataType:'jsonp',
        success:function(data){
            alert(data);
        }
    })
    

    The URL returns a .csv file, but I am specifying the jsonp 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 jsonp 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: http://jsfiddle.net/92uJ4/3/

    Any help is greatly appreciated.

    Tim