AlignedDev
AlignedDev

Reputation: 8233

jQuery and CORS

How should I approach this if the server doesn't respond with JSONP? I've tried several options with $.ajax, but can't get it to work.

CodePen Example

//var url = 'https://coinbase.com/api/v1/currencies/exchange_rates';
var url = 'http://blockchain.info/ticker';
$.ajax({
    type: 'GET',
    url: url,
    //jsonpCallback: 'jsonCallback',
    contentType: 'application/json',
    //async: false,
    //dataType: 'jsonp',

    //xhrFields: { 
    // for CORS?
    //  withCredentials: false
    //},
    success: function (json) {
        debugger;
    },
    error: function (json) {
     debugger;
    }
});

Upvotes: 1

Views: 4172

Answers (3)

Hassan Zaheer
Hassan Zaheer

Reputation: 1371

Request:

$.ajax({
            url: "http://yoururl",
            type: "POST",
            crossDomain: true,
            data: JSON.stringify(somejson),
            dataType: "json",
            success: function (response) {
                var resp = JSON.parse(response)
                alert(resp.status);
            },
            error: function (xhr, status) {
                alert("error");
            }
        });

Sample response from server (In Python - Django)

response = HttpResponse(json.dumps('{"status" : "success"}'))
response.__setitem__("Content-type", "application/json")
response.__setitem__("Access-Control-Allow-Origin", "*")

return response

Essentially you have to change the response headers on the server side.

Upvotes: 0

Joey Cody
Joey Cody

Reputation: 91

It looks like you're trying to send an AJAX request to blockchain.info and retrieve the JSON feed. Luckily they've added support for CORS.

Simply pass the parameter cors=true to the requested url (ex. http://blockchain.info/ticker?cors=true) and you should be able to grab the data.

Looks like CORS are only supported for a few API calls as per https://blockchain.info/api/blockchain_api.

Upvotes: 5

mcv
mcv

Reputation: 4459

It sounds like you're doing a cross-domain request to a server that doesn't support JSONP.

There's a good reason why browsers refuse data from servers that don't want their data to be used in cross-domain requests. If browsers didn't do that, there's be a ton of security problems all over the web. So the server needs to allow this for this to work.

There are basically two ways a server can allow this: the old ugly way through JSONP, but you say it doesn't support that. Though you could still try by changing your url to 'http://blockchain.info/ticker?callback=?' and datatype to jsonp.

But there's also the new, clean way with CORS headers. If the server adds a Accept-Control-Allow-Origin: * header to its response, anyone (using a modern browser) can use the data with a normal Ajax call.

If the server doesn't allow you to use its data, you're out of luck.

Upvotes: 0

Related Questions