0

I want to get JSON from the URL, but jQuery's function getJSON doesn't work. I got this error: "Failed to load https://bittrex.com/api/v1.1/public/getticker?market=usdt-btc: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access." What did I do wrong? Or should I use some other fucntion? Please help!

function ticker(url)
{
    this.Last = 0;

    $.getJSON(url, function(data)
    {
        this.Last = data.result.Last;
    });

    this.getFullInfo = function()
    {
        console.log("Last: " + this.Last);
    }
}

var usdtBTC = new ticker("https://bittrex.com/api/v1.1/public/getticker?market=usdt-btc");
usdtBTC.getFullInfo();
PoorProgrammer
  • 111
  • 1
  • 2
  • 9
  • 2
    Possible duplicate of [jQuery.getJSON - Access-Control-Allow-Origin Issue](https://stackoverflow.com/questions/6396623/jquery-getjson-access-control-allow-origin-issue) – Ele Feb 04 '18 at 20:42
  • Possible duplicate of [How to return value from an asynchronous callback function?](https://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function). Even if you do manage to fix the Access-Control-Allow-Origin issue, you still won't get the value with the way you wrote your code. – Mikey Feb 04 '18 at 20:45
  • Oh crickey! A downvote because I accidentally clicked send too early :o( – DJDaveMark Feb 04 '18 at 20:49

1 Answers1

2

A few things are wrong:

  1. That URL isn't accessible via AJAX for the whole world to see. Read up on CORS. The error actually comes from a HEAD request that the browser does automatically to see what hosts & methods are allowed to access the link.

  2. You need to bind the this param to the function or this will refer to the global scope (function-in-a-function):

$.getJSON(url, function(data) {
    this.Last = data.result.Last;
}.bind(this));
  1. If the request worked, you'd need to wait until the request had finished before calling getFullInfo() (just like a timeout), or this.Last would still be 0.

  2. You nearly always want to add a fail function especially when testing:

var url = "https://bittrex.com/api/v1.1/public/getticker?market=usdt-btc";
$.getJSON(url, function(data) {
    console.log(data.result);
}.bind(this))
.fail(function(jqxhr, textStatus, error) {
    var err = textStatus + ", " + error;
    console.log("Request Failed: " + err);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
DJDaveMark
  • 2,669
  • 23
  • 35