Search code examples
javascriptjqueryhtmlcross-domainjquery-csv

cross-domain requests - javascript


Background:

I am creating a web-app to download and display housing prices. Data source: http://www.fhfa.gov/DataTools/Downloads/Documents/HPI/HPI_AT_metro.csv

My Plan:

Download the data directly from the link using javascript, and then turn the data into a javascript object (possibly using jQuery-csv). After this, I would use DataTables or another javascript library to display the data.

Where I got stuck:

After some research, it appears doing this violates the "same-origin policy". From what I read, it is not acceptable to download data from external sources in javascript.

Questions:

  1. Am I correct? Does downloading a .csv from an external data source violate the "same-origin policy"?
    • If I am not correct, the pieces of code required to download the .csv from the link above and convert it into a javascript object (preferably using jQuery) would be extremely helpful.
  2. If I am correct, why is downloading an external .csv a violation of this policy, whereas sourcing an external image to be used in a website is not a violation of this policy? E.g.

<img src="http://www.freeflashgamearcade.com/games/images/tic-tac-toe.jpg">

Notes:

I am hoping to do it this way, so I can avoid using a server side language completely. If this does not work, I plan on setting up the app using python/flask, which would only be used to download the data.


Solution

  • There are a few problems with the project you want to achieve:

    1. You cannot use an AJAX request to download a third party file or fetch data because of the CORS policy. Sometimes a website will allow to share its resources and in that case getting 3rd party data via AJAX is possible. (https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS)

    2. Even if you were able to download the CSV file, you would have to parse it to display the data and since you are using JavaScript you will be downloading it on the client computer and then you will need to access it which is not possible. (You cannot access system files from the Javascript [more detail can be found here: Local file access with javascript)