Tag Archives: PHP

Easily Convert JSON to JSONP With A Simple PHP Snippet

Same origin policy issue errors when returning data from an API that only delivers JSON? This security measure happens because the browser dosen’t allow cross-origin data sharing. You need a server-side component that will go grab a JSON feed for you and convert it to JSONP. This code will retrieve the JSON inside a <script> tag (the exception to sharing resources cross-domain are <script> tags like when serving a cdn, or other type of javascript scripts, etc), and within that will be a callback function. This is the padding, which is what the P stands for in JSONP; here padding == script tags and a function delivering us a javascript object literal. When the script is called from a server it calls the function that delivers the fetched data and presents it as JSON.

Even if you’re not comfortable writing PHP; you can use this snippet to overcome same origin browser restrictions when making requests across domains.

<?php 
 header('Content-Type: application/javascript');
 $data = file_get_contents('http://url.com?whatever=' . $_GET['someData']);
 echo $_GET['callback'] . "(" . $data . ")";

Line 1 sets your HTTP MIME type of the body of the request, where ‘application’ is the type and ‘javascript’ is the subtype. More information about MIME types.
Line 2 defines a variable called $data that makes your GET request to the API
Line 3 echos (returns) a function whose name is the string ‘callback’. The callback function brings your JSON into your app inside script tags then when it execute. Congratulations you can now use a server-side component to access JSON across domains.

In your JS link to the PHP file in the AJAX call instead of the API URL since that action is now happening in the PHP GET. It should look something like the following:

getData = function(someData){
 $.ajax({
   url : './api.php', // route to the php file you just created
   type : 'GET',
   dataType : 'jsonp',
   data : {
     format : 'json',
     property : someData // property you are calling
   },
   success : function(results){
     return results; 
   } 
 });
};

If you are working locally at this point you will get an error. Make sure you are running the code on a server. That server needs to make the request. To continue working in the local environment you can use MAMP, a Node Server, browser-sync or pick your own other adventure, but the php needs to run on a server.

To make it clearer, here is code I have used to fetch the title of movies from this API:

<?php
   header('Content-Type: application/json');
   $data = file_get_contents('http://bechdeltest.com/api/v1/getMoviesByTitle?title=' . $_GET['title']);
   echo $_GET['callback'] . "(" . $data . ")";
getMovie = function(Title){   
  $.ajax({
    url : './api.php',
    type : 'GET',
    dataType : 'jsonp',
    data : {
      format : 'json',
      title : Title
    },
    success : function(results){
       displayTitle(results);
     } 
   });
};

View this code in use in my Bechdel Test web app.

I”ve seen people use this snippet to work easily with the following APIs to make apps:

500px API
Bechdel Test API
GoodReads API
Luminate Online API
Wakatime API

It is worth mentionning that there are some really well documented security issues with JSONP, specifically that JSONP can deliver any kind of JavaScript and you lose control over failures and other things you probably want to track. At time of writing CORS is the recommendation of the W3C, and opens up a lot more possibilities including doing more types of requests with data besides just GET.