0
    $.ajax({
  url: "http://192.168.153.131:8080/api/stats",
  type: "GET",
  dataType: 'JSONP',
  jsonpCallback: 'jsonCallback'
});

function jsonCallback(response) {
  console.log(JSON.parse(response));
}

I have a server that is serving JSON to this url and CORS is not able to be enabled so I need a way to get around that. I was trying to use JSONP but I cannot seem to get it to work.

this is the response that I am getting in the google chrome console:

{"time":1516239458,"global":{"workers":0,"hashrate":0},"algos":{"scrypt-n":{"workers":0,"hashrate":0,"hashrateString":"0.00 KH"}},"pools":{"garlicoin":{"name":"garlicoin","symbol":"GRLC","algorithm":"scrypt-n","poolStats":{"validShares":"198","validBlocks":"1","invalidShares":"7","totalPaid":0},"blocks":{"pending":1,"confirmed":0,"orphaned":0},"workers":{},"hashrate":0,"workerCount":0,"hashrateString":"0.00 KH"}}}

Which appears to be valid but it still throws an error.

  • First, need to figure out what piece of code is causing your error. Change your console.log to simply `console.log('hello world');` Still get an error? If so, the error is not being caused by json.parse obviously. When debugging, always start with trying to figure *what* exactly is causing the error. Until you know that, you won't be able to figure out *how* to fix it. – KayakinKoder Jan 18 '18 at 02:03
  • I did that and I am still getting the error any idea where I could go from here. – Kyle Rosenberg Jan 18 '18 at 02:08
  • 1
    That response is JSON, not JSONP. – Barmar Jan 18 '18 at 02:21
  • For JSONP, the response should begin with `jsonCallback({` – Barmar Jan 18 '18 at 02:21
  • 1
    It sounds like the API you're using doesn't actually implement JSONP. Changing the type from `json` to `jsonp` is not a magical way to get around CORS, it requires that the server cooperate. – Barmar Jan 18 '18 at 02:22
  • If I set the content type to JSON I get a Access-Control-Allow-Origin error I need a work around for this. – Kyle Rosenberg Jan 18 '18 at 02:23
  • @KyleRosenberg As Barmar already told you, you cannot work around this on the client side. Make the server cooperate by supporting JSONP or CORS (or both), or use a proxy on your own server. – Bergi Jan 18 '18 at 04:33

1 Answers1

0

You don't need to parse the response because is already parsed as a JSONObject

$.ajax({
    url: "http://192.168.153.131:8080/api/stats",
    type: "GET",
    dataType: 'JSONP',
    jsonpCallback: 'jsonCallback'
});

function jsonCallback(response) {
    console.log(response);
}
Ele
  • 33,468
  • 7
  • 37
  • 75