JavaScript: How to Create Jsonp

How to create JSONP callback?

Assuming it's exposed by some web-accessible method, you need to accept a callback (or similar) parameter which then just becomes a wrapper to the JSON data. e.g.

If you had:

/some/service.json

Which returned:

{"this":"is","JSON":"data"}

You then allow the service to be passed a callback:

/some/service.json?callback=foo

Which in turn results in:

foo({"this":"is","JSON":"data"})

That's all there really is to making the response adhere with JSONP.

How to make a jsonp request

I have decided to give a detailed description of how to do a jsonp request so others will not run into the same troubles as I did.

myApp.factory('users', function($http) {
return {
getUsers: function() {
var deferred = $q.defer();
var url = "http://localhost/api/api/index.php/analytics/UsersPerCube?callback=JSON_CALLBACK";
$http.get(url).success(function (data, status, headers, config) {
console.log(data);
deferred.resolve(data);
}).error(function (data, status, headers, config) {
//this always gets called
console.log(status);
deferred.reject(status);
});
return deferred.promise;

}

Notice that the url contains ?callback=JSON_CALLBACK. Here is a nice stackoverflow on that. Once you get the response then you'll receive a json like the one below.

"angular.callbacks._1( {"cube":"1","points":"160"},{"cube":"2","points":"690"},{"cube":"3","points":"331"})"

Here is a nice stackoverflow on that subject

Now the one part that got me is that the server has to return the GET param, callback. Here is a good tutorial for that. http://niryariv.wordpress.com/2009/05/05/jsonp-quickly/ So the json looks like the one above.

Well, I hope this helps someone in the future.

How do I set up JSONP?

Assuming your server is running PHP, you just need to add 'callback' GET request.

<?php header('content-type: application/json; charset=utf-8');
$data = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo $_GET['callback'] . '('.json_encode($data).')';

And on client side (using jQuery):

$.ajax({url: 'http://site.com/data.php', dataType:'jsonp'});

The PHP code above is just for demo, don't forget to sanitise $_GET['callback']

That said, if your issue just the same origin policy, you'll probably just need to allow cross-origin from the server side, and everything should work.

How to write JSONP Ajax request on pure js?

In this particular case, you aren't making an ajax call at all, instead you're making a JSONP request. Luckily, these are incredibly easy to replicate and work in all browsers.

var s = document.createElement("script"),
callback = "jsonpCallback_" + new Date().getTime(),
url = "http://forexplay.net/ajax/quotes.php?callback=" + callback;
window[callback] = function (data) {
// it worked!
console.log(data);
};
s.src = url;
document.body.appendChild(s);

What is JSONP, and why was it created?

It's actually not too complicated...

Say you're on domain example.com, and you want to make a request to domain example.net. To do so, you need to cross domain boundaries, a no-no in most of browserland.

The one item that bypasses this limitation is <script> tags. When you use a script tag, the domain limitation is ignored, but under normal circumstances, you can't really do anything with the results, the script just gets evaluated.

Enter JSONP. When you make your request to a server that is JSONP enabled, you pass a special parameter that tells the server a little bit about your page. That way, the server is able to nicely wrap up its response in a way that your page can handle.

For example, say the server expects a parameter called callback to enable its JSONP capabilities. Then your request would look like:

http://www.example.net/sample.aspx?callback=mycallback

Without JSONP, this might return some basic JavaScript object, like so:

{ foo: 'bar' }

However, with JSONP, when the server receives the "callback" parameter, it wraps up the result a little differently, returning something like this:

mycallback({ foo: 'bar' });

As you can see, it will now invoke the method you specified. So, in your page, you define the callback function:

mycallback = function(data){
alert(data.foo);
};

And now, when the script is loaded, it'll be evaluated, and your function will be executed. Voila, cross-domain requests!

It's also worth noting the one major issue with JSONP: you lose a lot of control of the request. For example, there is no "nice" way to get proper failure codes back. As a result, you end up using timers to monitor the request, etc, which is always a bit suspect. The proposition for JSONRequest is a great solution to allowing cross domain scripting, maintaining security, and allowing proper control of the request.

These days (2015), CORS is the recommended approach vs. JSONRequest. JSONP is still useful for older browser support, but given the security implications, unless you have no choice CORS is the better choice.

How to create JSON string in JavaScript?

Disclaimer: This is not an answer to follow for the best way how to create JSON in JavaScript itself. This answer mostly tackles the question of "what is the problem?" or WHY the code above does not work - which is a wrong string concatenation attempt in JavaScript and does not tackle why String concatenation is a very bad way of creating a JSON String in the first place.

See here for best way to create JSON: https://stackoverflow.com/a/13488998/1127761

Read this answer to understand why the code sample above does not work.

Javascript doesn't handle Strings over multiple lines.

You will need to concatenate those:

var obj = '{'
+'"name" : "Raj",'
+'"age" : 32,'
+'"married" : false'
+'}';

You can also use template literals in ES6 and above: (See here for the documentation)

var obj = `{
"name" : "Raj",
"age" : 32,
"married" : false,
}`;

Create a jsonp object dynamically in javascript(Send json object to Cross Domain)

You have to change the Datatype to JSONP

function hello(data){ // my call back function
console.log(data);
}

$(function(){
//It's not actually working, but htis code should work well
//Let's say that you put your docStats in an object
//like docStats = data.response.clickStats.docStats

$.ajax({
url:'http://example.com',
type : 'POST' ,
dataType: 'jsonp',
data : {
fq: 'param1',
wt: 'param2',
"json.wrf" : 'hello' // how i call my callback function

}
});

})


Related Topics



Leave a reply



Submit