Using JSONP to get JSON data from another server

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.

Answers:

Answer

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.

Answer

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).

Answer

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.

Answer

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 &amp; 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);

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.