Access the data form Coursera api using jquery jsonp

927 Views Asked by At

Today I was trying to access the coursera api using jquery after reading the Coursera catalog documentation. I wrote a code and got an error No 'Access-Control-Allow-Origin' header is present on the requested resource. So did some google and found that Jsonp can be used to make the cross domain request. So I simply used a $.ajax function to make a request to this url or say this simple url and some other such urls, but failed.

Data on the url is like {"elements":[{"id":2,"shortName":"ml","name":"Machine Learning","links":{}}],"linked":{}}

I wrote the following code.

$(document).ready(function() {
$.ajax({
    url: "https://api.coursera.org/api/catalog.v1/courses/2",
    type: "GET",
    dataType: 'jsonp',
    jsonpCallback: 'localJsonpCallback',
    contentType: 'application/json',
    success: function(){
        alert("success");
    },
    error:function(jqxhr, textStatus, error){
        alert("textStatus : " + textStatus + "\n error" + error);
    }   
  }); 

  function localJsonpCallback(data) {
  alert("localJsonpCallback : " + data);
  }
  });

The above code fails and goes to the error handler and the error its printing is , textstatus: parseError and Error: localJsonpCallback was not called. I am not getting whats wrong with the code. Moreover in the console I am getting the error Uncaught SyntaxError: Unexpected token : and 2?callback=localJsonpCallback&_=1418037208234:1 when using url https://api.coursera.org/api/catalog.v1/courses/2.

Is it necessary to use the jsonp call back function? Can't we handle the direct response in success handler.

3

There are 3 best solutions below

1
On BEST ANSWER

this works

you can handle directly in success callback

$(document).ready(function() {
  $.ajax({
    url: "https://api.coursera.org/api/catalog.v1/courses/2",
    type: 'GET',
    dataType: "json",
    success: function(data) {
        console.log(JSON.stringify(data,null,4));
    }
  }); 
});

returned

 {
    "elements": [
        {
            "id": 2,
            "shortName": "ml",
            "name": "Machine Learning",
            "links": {}
        }
    ],
    "linked": {}
}

hope this helps

1
On

try this:-

$(document).ready(function() {    
$.getJSON("https://api.coursera.org/api/catalog.v1/courses?ids=2,3&fields=language,shortDescription&includes=sessions&fields=status&categories", function (response) {
alert(JSON.stringify(response));
},'jsonp'); 
 });

Demo

0
On

In our case you don't need use jsonp, you can use usual ajax request

$.ajax({
    url: "https://api.coursera.org/api/catalog.v1/courses/2",
    type: "GET",
    dataType: 'json',
    success: function (res) {
      console.log(res);
    },
    error: function(jqxhr, textStatus, error) {
        alert("textStatus : " + textStatus + "\n error" + error);
    }
});

Demo: http://jsbin.com/payare/1/edit?js,console