By arnoldbird on
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
You want
You want drupal_json_output(); it'll set the necessary header. :)
Thanks, but that's what I
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?
Oh ha! Sorry, missed that.
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?
Ugh. Dumbest PHP mistake
Ugh. Dumbest PHP mistake ever, I'm pretty sure. Look how I'm populating the $arr array. Ooops! That won't do it!
Yeah I just saw that too
Yeah I just saw that too lol... Always something simple. :)
Sure enough, it works fine
Sure enough, it works fine when I fix the remedial PHP mistake.