Using JSONP to get JSON data from another server

You can use many ways but the two most convenient ones are either an AJAX call or to use jQuery’s getJSON() method

Using AJAX call

$(document).ready(function() {
  $(".btn").click(function() {
    $.ajax({type: "get",
            url: "http://api.forismatic.com/api/1.0/",
            data: {method: "getQuote",format: "jsonp",lang: "en"},
            dataType: "jsonp",
            jsonp: "jsonp",
            jsonpCallback: "myJsonMethod"
    }); 
  });
});
function myJsonMethod(response){
  console.log (response);
}

In the above method response Object has all the JSON data from the API call.

Using getJSON()

$(document).ready(function() {
  $(".btn").click(function() {
    $.getJSON("http://api.forismatic.com/api/1.0/?method=getQuote&format=jsonp&lang=en&jsonp=myJsonMethod&?callback=?");
  });
});
function myJsonMethod(response){
  console.log (response);
}

In the above method the same thing happens.

NOTE –> That JSONP takes the name of the callback function on which the response is to be sent.

Leave a Comment