In this article I will explain JSONP request with Callback example using JavaScript i.e. how to make a Cross Domain JSONP request with Callback using plain JavaScript without using jQuery.
Callback means that it will call the JavaScript function whose name is specified in the Callback parameter once the response is ready.
In order to explain JSONP Callback request using JavaScript, I am making call to a JSON Web Service which returns IP Address in JSON format with Callback.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
window.onload = function () {
//Create a SCRIPT element.
var script = document.createElement("script");
//Set the Type.
script.type = "text/javascript";
//Set the source to the URL the JSON Service.
script.src = "https://api.ipify.org?format=jsonp&callback=DisplayIP";
//Append the script element to the HEAD section.
document.getElementsByTagName("head")[0].appendChild(script);
};
function DisplayIP(response) {
document.getElementById("ipaddress").innerHTML = "Your IP Address is " + response.ip;
}
</script>
</head>
<body>
<span id="ipaddress"></span>
</body>
</html>
Explanation
Inside the window onload event handler, a dynamic Script Tag is created and its Type is set and Src attributes are set. Finally the Script Tag is added to the HEAD tag of the page.
Note: By default the browsers do not support Cross Domain calls i.e. Calls made to other website or domains and hence to make a Cross Domain call we need to attach the Script dynamically to the page as shown above.
As soon as the Script Tag is attached to the page, it makes call to the JSON Web Service along with the Callback function’s name DisplayIP as Callback parameter.
The JSON Web Service returns the response in the specified Callback JavaScript function DisplayIP, which accepts the JSON response and displays it in HTML Span element.
Demo
Downloads