Using JSONP to get JSON data from another server

22,005

Solution 1

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.

Solution 2

JSONP is a technique by which you put your request into a script tag URL (which is allowed to any domain) and you pass in that URL a parameter which indicates the name of a function that you want the resulting script that is returned to call and pass it your data. In this case it looks like you're specifying that the callback function is named getResults.

For JSONP to work, the server you are sending the request to must specifically support it because it requires a specific type of response format and it enables any domain from any browser to make the request which isn't something all sites want to enable.

So, the very first thing you need to find out is if the server you're requesting data from supports JSONP or not and if so, make sure you understand exactly how it will format the response and how it is expecting the callback function to be specified (common convention is with the callback=xxx URL parameter, but it doesn't have to be done that way.

If the server you want data from does not support JSONP, then you simply can't use JSONP to get data from it. If it doesn't support some other cross domain request strategy, then you can't get data from it via a browser web page and will have to do the request from something other than a browser (like another server).

Solution 3

live sample from here:

JSONP - JSON with padding, ie. javascript object wrapped in a callback, in our case it's jsonCallback

this is content of file:

jsonCallback(
    {
        "sites":
        [
            {
                "siteName": "JQUERY4U",
                "domainName": "http://www.jquery4u.com",
                "description": "#1 jQuery Blog for your Daily News, Plugins, Tuts/Tips & Code Snippets."
            },
            {
                "siteName": "BLOGOOLA",
                "domainName": "http://www.blogoola.com",
                "description": "Expose your blog to millions and increase your audience."
            },
            {
                "siteName": "PHPSCRIPTS4U",
                "domainName": "http://www.phpscripts4u.com",
                "description": "The Blog of Enthusiastic PHP Scripters"
            }
        ]
    }
);

code for retrieving a file:

(function($) {
var url = 'http://www.jquery4u.com/scripts/jquery4u-sites.json?callback=?';

$.ajax({
   type: 'GET',
    url: url,
    async: false,
    jsonpCallback: 'jsonCallback', <-- callback here
    contentType: "application/json",
    dataType: 'jsonp',
    success: function(json) {
       console.dir(json.sites);
    },
    error: function(e) {
       console.log(e.message);
    }
});

})(jQuery);

Solution 4

JSONP is a method that the server has to implement.

If you are sure the server accepts and understands JSONP, then maybe the parameter you use to pass the callback name is not callback. See their documentation if they have one.

Otherwise, you simply can't get the json data from a browser.

Share:
22,005
user3299416
Author by

user3299416

Updated on July 09, 2022

Comments

  • user3299416
    user3299416 almost 2 years

    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.

  • user3299416
    user3299416 about 10 years
    How would I find out if the server supports JSONP?
  • jfriend00
    jfriend00 about 10 years
    @user3299416 - you have to look in the documentation for that site's API to see what it supports. You may also have to make the request a certain way for it to know that you're asking it to do JSONP.
  • Si8
    Si8 over 7 years
    I get this error: Uncaught SyntaxError: Unexpected token :
  • Alee
    Alee over 6 years
    in your first example "Using Ajax Call", you use type:"POST". JSONP is only for GET request. JSONP acts like a <script> tag, so you can only use GET with it, not POST.