A Quick JSONP Example

Sometimes when people write out their blog posts they forget to proof it for validation. I had a dandy time trying to get a form to submit via JSONP. After struggling through tutorials, I finally got something working. Why not write a blog post about it? First off JSONP is JSON but with the ability to go cross domain. The setup from regular JSON is similar and I will post both just so that I have the reference for them. First off JSON:

$.ajax({ //ajax call starts
type: "POST",
url: 'api/api.php', //Jquery loads api.php
data: $('#loginForm').serialize(), //sending the paramaters of the form
dataType: 'json', //choosing a JSON datatype
success: function(data){
//Do stuff with the data object
error: function(XMLHttpRequest, textStatus, errorThrown){
//Alert or console log some errors

And now JSONP:

$.ajax({ //ajax call starts
url: 'http://webaddress/somefile.php?callback=?', //Jquery loads api.php
data: $('#loginForm').serialize(), //send value of the button clicked
dataType: 'jsonp', //choosing a JSON datatype
jsonp: "callback",
jsonpCallback: "returnJson"

function returnJson(rtndata){
console.log("Return Data As follows");

You have to declare your own callback function that will be called. The server part is a similar in both cases. You use POST in JSON and GET with JSONP and the function json_encode(“return data”) to return information back. The PHP for JSONP must include the line header(‘Content-Type: application/json’);. First the JSON server:

postAction = (isset($_POST['action']) ? $_POST['action'] : null);
if($postAction == 'login'){
    echo json_encode("I got the action variable");
} else {
    echo json_encode("There was a problem");

And now the JSONP Server Example:

header('Content-Type: application/json');
if (isset($_GET['id'])){
	$rtnjsonobj->id = $_GET['id'];
$rtnjsonobj->message = "You got an AJAX response via JSONP from another site!";
echo $_GET['callback']. '('. json_encode($rtnjsonobj) . ')';

I should mention my examples aren’t the best but I wanted to use the working code so that I knew the examples would work. With these few examples you should be able to fulfill all your JSON/JSONP requirements. You can also use the $.getJSON method as well like the following:

	function(data){ console.log(data.message) }

This will work as well I just prefer to use the json method.