How to return json?

In my js, I have...

var posturl = '/mymodule/my/callback';
$.post(posturl, {}, function(r) {
    console.log(r);
}, "json");

In my PHP...

function mymodule_page_my_callback() {

  $arr['apple'];
  $arr['banana'];
  
  drupal_json_output($arr);
// also tried: ajax_deliver($arr);
// also tried: print json_encode($arr);
// also had a look at the ajax example module but it does not use json.
  
}

In the firebug console I get a null response.

Thanks for your help.

Comments

roper.’s picture

You want drupal_json_output(); it'll set the necessary header. :)

arnoldbird’s picture

Thanks, but that's what I have in the code I posted. Doesn't work. I mean, doesn't seem to work. Something wrong in my js that you can see?

roper.’s picture

Oh ha! Sorry, missed that. :P

What happens when you just try to hit the page in your browser? You should see the raw JSON there... I'm assuming you have implemented hook_menu() to define your page callback right?

arnoldbird’s picture

Ugh. Dumbest PHP mistake ever, I'm pretty sure. Look how I'm populating the $arr array. Ooops! That won't do it!

roper.’s picture

Yeah I just saw that too lol... Always something simple. :)

arnoldbird’s picture

Sure enough, it works fine when I fix the remedial PHP mistake.