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

[eluser]tharri[/eluser]
I have set up my server so that when it gets a request for this:

http://www.domain.com/feed/json

... it will correctly serve JSON data.

If there is a request for this:

http://www.domain.com/feed/json?callback=something

... 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:

http://twitter.com/users/buzzfeed.json
http://twitter.com/users/buzzfeed.json?c...ckfunction

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.


#2

[eluser]tharri[/eluser]
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:

parse_str(server('QUERY_STRING'),$_GET);

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

Code:
parse_str(server('QUERY_STRING'),$_GET);
if (get('callback')) {
  $jsonp = $this->input->get('callback').'('.$json .')';
}

Hope this helps someone else in the future! =P
#3

[eluser]arkin[/eluser]
Code:
echo $this->input->get('callback') . '(' . $json . ')';

voila!
#4

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

Code:
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.
#5

[eluser]arkin[/eluser]
Ah makes sense. You don't need parse_str(server('QUERY_STRING'),$_GET); either.
#6

[eluser]tharri[/eluser]
[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