Using JSONP to get JSON data from another server

html, javascript, jquery, json, jsonp

Solution

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.

Problem

I'm trying to collect JSON data from a website hosted by a company. I am not on the same domain, so I can't just access it. From the headers, it seems that they don't use CORS either. So I've tried to use JSONP to parse the data, but it doesn't seem to work. I've tried doing $.getJSON and $.ajax, but those throw errors and don't call the function. This is my solution thus far, and in the response from the server, it still doesn't wrap the data in getResults. ``` <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <script type="text/javascript" src="jquery/js/jquery-1.9.0.min.js"></script> <script> function getResults(data) { console.log(data[0].name); } </script> <script type='text/javascript' src='https://solstice.applauncher.com/external/contacts.json?callback=getResults'></script> ``` I'm fairly new to HTML, JavaScript, and jQuery, so I'm just really confused why the response is being wrapped in the function and console log isn't working. Any help would be appreciated.

Original source