Search code examples
javascriptjsonp

This jsonp should be working so easily, what am I doing wrong?


I am trying to use asynchronous jsonp to display live prices on a webpage:

function addscript () {
    var url = "http://wdcticker.com/api/ticker?callback=updatePrices" + "&random=" + (new Date()).getTime();
    var newScript = document.createElement("script");
    newScript.setAttribute("src",url);
    newScript.setAttribute("id","jsonp");
    var oldScript = document.getElementById("jsonp");
    var head = document.getElementsByTagName("head")[0];
    if (oldScript == null) {
        head.appendChild(newScript);
    } else {
        head.replaceChild(newScript, oldScript);
    }
    console.log('done');

}

function updatePrices(result){
    alert('got here');
    $('#wdcusd').text(result.wdc_usd_avg);
    $('#wdcbtc').text(result.wdc_btc_avg);
}

The addscript function is called successfully every 10 seconds. The callback function updatePrices() is not being called. The error my console is showing is:

SyntaxError: missing ; before statement

"btc_e_btc_set": true,

even though the json at http://wdcticker.com/api/ticker passes json lint perfectly. What am I doing wrong!!? This should be so simple!


Solution

  • If http://wdcticker.com/api/ticker?callback=updatePrices supported JSONP you would expect to see this as the response at that url:

    updatePrices({
      // JSON here
    });
    

    Instead, it simply returns raw JSON like this:

    {
      // JSON here
    }
    

    So it would appear that the server you are trying to connect to does not support JSONP, and server side support is required. You cannot use JSONP with any JSON API, the API server must explicitly support and allow JSONP.