JSONP stands for JSON with Padding. Requesting a file from another domain can cause problems, due to cross-domain policy. Requesting an external script from another domain does not have this problem. JSONP uses this advantage, and request files using the script tag instead of the XMLHttpRequest object.
Use cases
- Javscript widgets – eg: Newsletter subscription forms, Survey forms
- Analytics and statics – eg: Alternative to google analytics
Below is an example source code, How newsletter subscription form can be added to any web page, just by injecting some JavaScript and html tag.
index.html
This file is main file where we need to inject, two elements. ( index.js in script tag & widgetcontainer div) for rendering the subscription widget)
<!DOCTYPE html>
<html>
<head>
<title>Subscriber to Newsletter</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<script type="text/javascript" src="index.js"></script>
</head>
<body>
<div id="widgetcontainer"></div>
</body>
</html>
HTMLindex.js
This file is main JavaScript file which has JSONP call to server and rendering widget to widgetcontainer div.
jQuery(document).ready(function() {
jQuery.ajax({
type: 'GET',
url: 'data.php?callback=?',
data: {
url: window.location.href
},
cache: false,
dataType: 'jsonp',
success: function (response) {
jQuery('#widgetcontainer').html(response);
},
error: function (jqXHR, exception) {
console.log(jqXHR);
}
});
});
JavaScriptdata.php
This file is server side php file to send widget HTML from server in JSONP ajax request.
<?php
header('Content-type: application/x-javascript');
$callback = $_GET["callback"];
$data = $_GET;
//Do stuff with request data
// Include widget file and serve in response
$widget = file_get_contents(__DIR__.'/widget.html');
echo $callback . '('.json_encode($widget) .')';
exit;
PHPwidget.html
This file contains the whole UI and widget data submission to server logic. data.php file includes widget.html file and render.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Subscriber to Newsletter</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("#subnewsletterform").submit(function(e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var actionUrl = form.attr('action');
jQuery.ajax({
type: "POST",
url: actionUrl,
data: form.serialize(), // serializes the form's elements.
cache: false,
success: function(data) {
console.log(data); // show response from the php script.
jQuery("#subnewsletterform").trigger("reset");
jQuery('#resmsg').show();
},
error: function (jqXHR, exception) {
console.log(jqXHR);
}
});
});
});
</script>
</head>
<body>
<div class="container">
<h2>Subscriber to Newsletter</h2>
<form id="subnewsletterform" action="submit.php">
<div class="form-group">
<label for="email">Your Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter your email" name="email">
</div>
<button type="submit" class="btn btn-default">Subscribe</button>
<div id="resmsg" class="alert alert-success" style="display: none;">
<strong>Success!</strong> Thanks for subscribing.
</div>
</form>
</div>
</body>
</html>
HTMLsubmit.php
This file is server side php file to capture the data submitted from widget.html file form.
<?php
header('Content-type: application/json');
$data = $_POST;
//Do stuff with request
echo json_encode(['submitted' => true, 'data' => $data]);
exit;
PHPBelow attached complete source code of the example discussed above.