1

In my project I have to integrate the library and parse the files presented in csv format. To access the library and get the information form that file I use $ajax as follows:

<script>
  $(document).ready(function(){
  $.ajax({
      type: "GET",
      url: "http://stats.xxx.tv/osexternal/reports/xxxxx/xxx_2014_YTD/2014-03-12.csv",
      contentType: 'application/json',
      dataType: 'json',  
      username: 'xxxx@xxxx.com',
      password: 'dT$xxxx%949',
      success: function (){
          console.log('success');
      },
      error: function(jqXHR, textStatus, errorThrown) {
        console.log(textStatus, errorThrown);
      }
     });
  });
<script>

Can anyone let me know what's the wrong with this approach as I am getting cross domain problem.And please let me know any alternatives by using gems. Thanks for your help in advance!

pramod
  • 2,258
  • 1
  • 17
  • 22

1 Answers1

1

What you're running into appears to be a CORs issue of some kind. Things to note about CORs issues:

  • It is a security policy for Javascript, so it only affects calls in/from JS.
  • Being able to access it from the browser 'directly' doesn't have anything to do with CORs
  • CORS can be really irritating

Now, on how to solve it, you can try adding:

with_credentials: true to the Ajax arguments, but I have a feeling it's going to be something weirder than that... as well, since you have to include a username and password it's probably best not to expose those on the client for anyone to have...

So, what I'd do is make the call on the server (example is for a rails controller action, but the method could be used in a Sinatra app just the same) then return the CSV to the browser:

require 'net/http'
class MyController < ActionController::Base
  # ...
  def get_csv
    uri = URI('http://stats.adap.tv/osexternal/reports/xxxxx/xxx_2014_YTD/2014-03-12.csv')
    csv_request = Net::HTTP::Get.new(uri)
    csv_request.basic_auth("username", "password")
    csv_data = csv_request.request.body
    csv
  end
end

I'm assuming you are using Ruby because of your "gems" reference. Here's the doc for Net::HTTP

http://ruby-doc.org/stdlib-2.1.1/libdoc/net/http/rdoc/Net/HTTP.html

and a slightly easier to digest version:

http://www.rubyinside.com/nethttp-cheat-sheet-2940.html

In general, it'll always be easier (and safer) to have your server make a request to an external host (this is a broad generalization and there are absolutely cases where this isn't what you want). If you need to make a cross domain request I'd suggest starting with:

http://www.html5rocks.com/en/tutorials/cors/

It'll probably give you some good tips to figure out why it's not currently working.

Best,

tehprofessor
  • 2,957
  • 1
  • 21
  • 22