How to make a JSONP request from Javascript without JQuery?

Can I make a cross-domain JSONP request in JavaScript without using jQuery or other external library? I would like to use JavaScript itself and then parse the data and make it an object so I could use it. Do I have to use an external library? If not, how can I do it?

function foo(data)
    // do stuff with JSON

var script = document.createElement('script');
script.src = '//'

// or document.head.appendChild(script) in modern browsers

Lightweight example (with support for onSuccess and onTimeout). You need to pass callback name within URL if you need it.

var $jsonp = (function(){
  var that = {};

  that.send = function(src, options) {
    var callback_name = options.callbackName || 'callback',
      on_success = options.onSuccess || function(){},
      on_timeout = options.onTimeout || function(){},
      timeout = options.timeout || 10; // sec

    var timeout_trigger = window.setTimeout(function(){
      window[callback_name] = function(){};
    }, timeout * 1000);

    window[callback_name] = function(data){

    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.async = true;
    script.src = src;


  return that;

Sample usage:

$jsonp.send('some_url?callback=handleStuff', {
    callbackName: 'handleStuff',
    onSuccess: function(json){
        console.log('success!', json);
    onTimeout: function(){
    timeout: 5

At GitHub:

What is JSONP?

The important thing to remember with jsonp is that it isn't actually a protocol or data type. Its just a way of loading a script on the fly and processing the script that is introduced to the page. In the spirit of JSONP, this means introducing a new javascript object from the server into the client application/ script.

When is JSONP needed?

It is 1 method of allowing one domain to access/ process data from another in the same page asyncronously. Primarily, it is used to override CORS (Cross Origin Resource Sharing) restrictions which would occur with an XHR (ajax) request. Script loads are not subject to CORS restrictions.

How is it done

Introducing a new javascript object from the server can be implemented in many ways, but the most common practice is for the server to implement the execution of a 'callback' function, with the required object passed into it. The callback function is just a function you have already set up on the client which the script you load calls at the point the script loads to process the data passed in to it.


I have an application which logs all items in someone's home. My application is set up and I now want to retrieve all the items in the main bedroom.

My application is on The apis I need to load data from are on

Unless the server is explicitly set up to allow it, I cannot use ajax to load this data, as even pages on separate subdomains are subject to XHR CORS restrictions.

Ideally, set things up to allow x-domain XHR

Ideally, since the api and app are on the same domain, I might have access to set up the headers on If I do, I can add an Access-Control-Allow-Origin: header item granting access to Assuming the header is set up as follows: Access-Control-Allow-Origin: "", this is far more secure than setting up JSONP. This is because can get everything it wants from without giving CORS access to the whole internet.

The above XHR solution isn't possible. Set up JSONP On my client script: I set up a function to process the reponse from the server when I make the JSONP call.:

function processJSONPResponse(data) {
    var dataFromServer = data;

The server will need to be set up to return a mini script looking something like "processJSONPResponse({"room":"main bedroom","items":["bed","chest of drawers"]});" It might be designed to return such a string if something like // is called.

Then the client sets up a script tag as such:

var script = document.createElement('script');
script.src = '//';


This loads the script and immediately calls window.processJSONPResponse() as written/ echo/ printed out by the server. The data passed in as the parameter to the function is now stored in the dataFromServer local variable and you can do with it whatever you need.

Clean up

Once the client has the data, ie. immediately after the script is added to the DOM, the script element can be removed from the DOM:


My understanding is that you actually use script tags with JSONP, sooo...

The first step is to create your function that will handle the JSON:

function hooray(json) {
    // dealin wit teh jsonz

Make sure that this function is accessible on a global level.

Next, add a script element to the DOM:

var script = document.createElement('script');
script.src = '';

The script will load the JavaScript that the API provider builds, and execute it.

the way I use jsonp like below:

function jsonp(uri) {
    return new Promise(function(resolve, reject) {
        var id = '_' + Math.round(10000 * Math.random());
        var callbackName = 'jsonp_callback_' + id;
        window[callbackName] = function(data) {
            delete window[callbackName];
            var ele = document.getElementById(id);

        var src = uri + '&callback=' + callbackName;
        var script = document.createElement('script');
        script.src = src; = id;
        script.addEventListener('error', reject);
        (document.getElementsByTagName('head')[0] || document.body || document.documentElement).appendChild(script)

then use 'jsonp' method like this:



JavaScript XMLHttpRequest using JsonP (talk about the way of use Promise)

I have a pure javascript library to do that

Take a look at it and let me know if you need any help using or understanding the code.

Btw, you have simple usage example here:

 * Loads data asynchronously via JSONP.
const load = (() => {
  let index = 0;
  const timeout = 5000;

  return url => new Promise((resolve, reject) => {
    const callback = '__callback' + index++;
    const timeoutID = window.setTimeout(() => {
      reject(new Error('Request timeout.'));
    }, timeout);

    window[callback] = response => {

    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.async = true;
    script.src = url + (url.indexOf('?') === -1 ? '?' : '&') + 'callback=' + callback;

Usage sample:

const data = await load('');

I wrote a library to handle this, as simply as possible. No need to make it external, its just one function. Unlike some other options, this script cleans up after itself, and is generalized for making further requests at runtime.

function jsonp(url, key, callback) {

    var appendParam = function(url, key, param){
            return url
                + (url.indexOf("?") > 0 ? "&" : "?")
                + key + "=" + param;

        createScript = function(url, callback){
            var doc = document,
                head = doc.head,
                script = doc.createElement("script");

            .setAttribute("src", url);


                }, 0);

        q =
            "q" + Math.round(Math.random() *;

        appendParam(url, key, q), function(remove){
            window[q] =
                    window[q] = undefined;

Please find below JavaScript example to make a JSONP call without JQuery:

Also, you can refer my GitHub repository for reference.

window.onload = function(){
    var callbackMethod = 'callback_' + new Date().getTime();

    var script = document.createElement('script');
    script.src = ''+callbackMethod;


    window[callbackMethod] = function(data){
        delete window[callbackMethod];

 * Get JSONP data for cross-domain AJAX requests
 * @private
 * @link
 * @param  {String} url      The URL of the JSON request
 * @param  {String} callback The name of the callback to run on load
var loadJSONP = function ( url, callback ) {

    // Create script with url and callback (if specified)
    var ref = window.document.getElementsByTagName( 'script' )[ 0 ];
    var script = window.document.createElement( 'script' );
    script.src = url + (url.indexOf( '?' ) + 1 ? '&' : '?') + 'callback=' + callback;

    // Insert script tag into the DOM (append to <head>)
    ref.parentNode.insertBefore( script, ref );

    // After the script is loaded (and executed), remove it
    script.onload = function () {


 * Example

// Function to run on success
var logAPI = function ( data ) {
    console.log( data );

// Run request
loadJSONP( '', 'logAPI' );

If you are using ES6 with NPM, you can try node module "fetch-jsonp". Fetch API Provides support for making a JsonP call as a regular XHR call.

Prerequisite: you should be using isomorphic-fetch node module in your stack.

Just pasting an ES6 version of sobstel's nice answer:

send(someUrl + 'error?d=' + encodeURI(JSON.stringify(json)) + '&callback=c', 'c', 5)
    .then((json) => console.log(json))
    .catch((err) => console.log(err))

function send(url, callback, timeout) {
    return new Promise((resolve, reject) => {
        let script = document.createElement('script')
        let timeout_trigger = window.setTimeout(() => {
            window[callback] = () => {}
            reject('No response')
        }, timeout * 1000)

        window[callback] = (data) => {

        script.type = 'text/javascript'
        script.async = true
        script.src = url