Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 913
user3299416 Avatar asked Feb 11 '14 23:02

user3299416


People also ask

How do I get JSONP data?

Method to use JSONP:In HTML code, include the script tag. The source of this script tag will be the URL from where the data to be retrieve. The web services allow to specify a callback function. In the URL include the callback parameter in the end.

What is the difference between JSON and JSONP?

Json is stardard format that is human readable used to transmit information from one server to another server. Jsonp is a json with ability to transmit information to another domain. JSONP is JSON with padding, that is, you put a string at the beginning and a pair of parenthesis around it.

Is JSONP deprecated?

Yes, JSONP is obsolete now. There's absolutely no reason to offer a JSONP service anymore.

What is JSONP used for?

JSONP is a method for sending JSON data without worrying about cross-domain issues. JSONP does not use the XMLHttpRequest object. JSONP uses the <script> tag instead.


3 Answers

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.

like image 88
Harshit Anand Avatar answered Oct 23 '22 17:10

Harshit Anand


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

like image 38
jfriend00 Avatar answered Oct 23 '22 17:10

jfriend00


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);
like image 30
Eugene P. Avatar answered Oct 23 '22 18:10

Eugene P.