Welcome Guest, Not a member yet? Register   Sign In
Serving JSON & JSONP: Adding ?callback=function to a URL

I have set up my server so that when it gets a request for this:


... it will correctly serve JSON data.

If there is a request for this:


... it should serve JSONP data -- that is, JSON data wrapped in a function called "something".

The problem is, how do I get the value of callback? When I print_r($_GET), it is empty.

The only way I've been able to figure out is to use the PHP explode function to convert server('QUERY_STRING') into an array and check each key/value pair for callback. Is there an easier way?

And yes, I know I could change the URL structure, but it has basically become a "standard" that a json page can be converted to jsonp by adding "?callback=function" to the end of the URL. For example, see these two links:


The first is JSON. The second is JSONP. Many javascript libraries, including JQuery (I think) use that syntax, so I'd like to be able to support it.

Also, I don't want to set $config[‘enable_query_strings’] = TRUE because everywhere else on the site, I don't want it to accept query strings. I want it to use the standard domain.com/controller/function/id format.


lol... I searched and searched before posting that question, but after my continued search, I found the answer.

In short, in the function that outputs json (happens to be called json), I just need to add this:


I can then check for the presence of $_GET or get('callback') like normal.

if (get('callback')) {
  $jsonp = $this->input->get('callback').'('.$json .')';

Hope this helps someone else in the future! =P

echo $this->input->get('callback') . '(' . $json . ')';


Ah, right arkin. I forgot to mention that get() is one of my alias functions in a helper file:

function get($index, $clean = TRUE)
$CI =& get_instance();
return $CI->input->get($index, $clean);

I changed the code above to reflect the correct code for people who don't use such a function.

Ah makes sense. You don't need parse_str(server('QUERY_STRING'),$_GET); either.

[quote author="arkin" date="1336619183"]Ah makes sense. You don't need parse_str(server('QUERY_STRING'),$_GET); either.[/quote]

I believe I do. It doesn't work without it.

$config[‘enable_query_strings’] is set to FALSE in my config file.

Theme © iAndrew 2016 - Forum software by © MyBB