Search code examples
jqueryajaxapijsonpcoursera-api

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.


Solution

  • 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