# JSONP

JSONP stands for JSON with Padding. It is an alternate way to get around CORS issues. Server-side pass throughs are a common solution, JSONP is the other solution.

CORS restricts calls made via XMLHttpRequest( ) and fetch( ). However, we can load any script we want through an HTML <script> tag.

<script src="app.js"></script>
<!-- <script src="http://www.example.com/data.js"></script> -->
<script src="http://www.example.com/data.js?callback=myfunc"></script>
1
2
3

The first script tag is your local javascript file. The second is a normal request for a JavaScript file. The third one is requesting the same JavaScript file but also includes a querystring parameter. The third one is what a JSONP request looks like. We don't need the commented one.

The server that hosts the javascript must support JSONP. There must be some server-side code that alters the contents of the JavaScript file. If the original version of the JavaScript file looked like this

{
  "pets": [
    { "name": "Bob", "age": 2 },
    { "name": "Jesse", "age": 4 },
    { "name": "Woody", "age": 14 }
  ]
}
1
2
3
4
5
6
7

Then the JSONP version could look like this:

myfunc(
  {"pets": [
  {"name":"Bob", "age": 2},
  {"name":"Jesse", "age": 4},
  {"name":"Woody", "age": 14}]};
));
1
2
3
4
5
6

The "data" which comprised the whole file is now wrapped inside a call to a function called myfunc. The data becomes a parameter being passed to the function.

In your other JavaScript file, the one you created in your project, you will have a function called myfunc.

function myfunc(data) {
  //'data' is now the data that came from the external source
}
1
2
3

So, we pass the name of our function as a querystring parameter to the external URL. The URL might point to a file with a .js extension, a .php extension, or no extension. The important thing is that what gets returned is JavaScript. That JavaScript will be formatted as a bunch of JSON data, WRAPPED in a function call.

In our own JavaScript code we create the function with the same name that we pass as a querystring parameter. Our function will be called by the JavaScript file that comes back from the external server. Our function runs and accepts all that external data as its' input parameter.

# Restrictions

The external data source must have code that accepts the request including the querystring parameter. The external course will have a specific name for the querystring parameter, although callback is a common one.

We must have a function in our code that matches the name of the one that we send in the querystring.

Back to Week main page

Last Updated: 11/1/2020, 2:32:17 PM