Create a JavaScript jsonP Class

Classic AJAX requests are limited to the same domain. JSON with padding allows us to make requests to different domains. Below is an example of how to create a jsonP class, and handle requests using PHP.

JSON with padding works by making a JavaScript script request, using a SCRIPT tag and a callback function. The back end, in this example a PHP script, generates a JavaScript response wrapped around the callback function's name. For each request, the JavaScript object below appends a new script tag, and generates a random function name, which in turn calls a user defined function bound to an optional scope.

var JsonP = function() {
	// Class constructor. Do nothing.
}

// Method used for appending the script tag, to the document body
JsonP.prototype.appendBodyScript = function( url, funcName ) {
	// Create the tag
	var element = document.createElement( 'script' );
	element.src = url + '?cb=' + funcName
	// Append to body
	document.body.appendChild( element );
}

// Method used for generating a long random number
JsonP.prototype.generateRandomNumber = function() {
	return Math.floor( Math.random() * 100000000000 );
}

// Method used for generating the random function name, and function
JsonP.prototype.generateFunc = function( cb, scope ) {
	// Generate random function name
	var funcName = 'jsonP' + this.generateRandomNumber();
	while ( typeof window[funcName] !== "undefined" ) {
	// Ensure we don't overwrite existing functions
		funcName = 'jsonP' + this.generateRandomNumber();
	}
	// NOTE: Function must be global, for the server generated script to be able to issue a call
	window[funcName] = function( response ) {
		if ( scope ) {
			cb.bind( scope )( response );
		} else {
			cb( response );
		}
	}
	return funcName;
}

// Method used for issuing a call
JsonP.prototype.get = function( url, cb, scope ) {
	this.appendBodyScript( url, this.generateFunc( cb, scope ) );
}

// Example usage
var testJsonP = new JsonP();
testJsonP.get(
	'http://localhost/'
	,function( response ) {
		console.log( this );
		console.log( response );
	}
	,{
		name: 'Test Scope'
	}
);

Example PHP Script:

<?php

// Generate response
echo htmlspecialchars( $_GET['cb'] ) . "( " . json_encode( array( "A", "B" ) ) . " )";

Note how the PHP code essentially wraps the JSON response around the callback function name.

Leave a Reply

Your email address will not be published. Required fields are marked *