Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access the data form Coursera api using jquery jsonp

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.

like image 583
Ankit Kulkarni Avatar asked Mar 17 '23 16:03

Ankit Kulkarni


2 Answers

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

like image 123
Todd Avatar answered Mar 23 '23 19:03

Todd


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

like image 20
Mohit Kumar Avatar answered Mar 23 '23 17:03

Mohit Kumar