JavaScript Xmlhttprequest Using JSONp

JavaScript XMLHttpRequest using JsonP

JSONP does not use XMLHttpRequests.

The reason JSONP is used is to overcome cross-origin restrictions of XHRs.

Instead, the data is retrieved via a script.

function jsonp(url, callback) {
var callbackName = 'jsonp_callback_' + Math.round(100000 * Math.random());
window[callbackName] = function(data) {
delete window[callbackName];
document.body.removeChild(script);
callback(data);
};

var script = document.createElement('script');
script.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' + callbackName;
document.body.appendChild(script);
}

jsonp('http://www.helloword.com', function(data) {
alert(data);
});

In interest of simplicity, this does not include error handling if the request fails. Use script.onerror if you need that.

How to perform Ajax call with JSONP request in JavaScript?

I get error as Reason: CORS header ‘Access-Control-Allow-Origin’
missing.

This is because you're using XMLHttpRequest and usage of XMLHttpRequest requires CORS. The JSONP technique doesn't involve usage of XMLHttpRequest. The trick in JSONP is to create a script tag and let a browser load that script:

var script = document.createElement('script');
script.src = '//domain.com/path/to/jsonp?callback=my_callback_method'

document.getElementsByTagName('head')[0].appendChild(script);

Also, you need to create a global function, in your case its my_callback_method, and call it from the jsonp script.

Certainly, you server side should have implementation that when a request to //domain.com/path/to/jsonp is obtained, it should return a js document with a call to a global function specified in callback=my_callback_method:

my_callback_method()

JSONP with native XMLHttpRequest

JSONP is a JavaScript program and there is no good way to parse it. You either have to trust that it isn't going to vary the format or you have to execute third party code (the latter being how it is designed to be used, it's a relatively dangerous hack, which is why we now have CORS so we don't need JSONP). You could also write a complete JavaScript parser (in JavaScript!) and use it to find the function with the name that matches the callback, but that's rather non-trivial.

There is a third way though. If you remove callback=... from the URL then the service will return JSON instead of JSONP. Then you can just use JSON.parse() cleanly.

JSONP and XMLHttpRequest question

So is XMLHTTPRequest() supposed to return only javascript or html?

It can return any text you like (and maybe binary data, but I've never see that tried so I won't swear to it)

Can it not return a pure json document?

It can.

I thought the same origin policy does not apply to XMLHttpRequest() call.

The same origin policy most definitely does apply to XHR

Why is there a need to inject a tag into the DOM to make a call to a third party server?

The same origin policy is bypassed by loading a script (with embedded data) from another origin.

This is because you aren't reading a remote resource using JavaScript. You are executing some remote JavaScript which comes with embedded data.

At the end of it I did not understand JSONP at all. Can some one explain or refer me to a better explanation please?

JSON-P is just loading some JavaScript from another origin. That JavaScript consists of a single function call (to a function you define before adding the <script> element) with a single argument (a JS object or array literal).

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

Make XmlHttpRequest POST using JSON

If you use JSON properly, you can have nested object without any issue :

var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
var theUrl = "/json-handler";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "email": "hello@user.com", "response": { "name": "Tester" } }));

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.



Related Topics



Leave a reply



Submit