1

I'm trying to post data from ajax to php page which I made in the hook_menu, called "handler". So I have "domain.com/handler" which I try to do this in it:

function handler(){
  print_r($_POST);
}

and the hook looks like this:

$items['handler'] = array(
  'title' => 'Handler',
  'description' => 'handler for File Upload',        
  'page callback' => 'handler',
  //'access arguments' => array('access my_module_name via ajax'),
  'access arguments' => array('access example ajax'),
  'type' => MENU_CALLBACK
);

and on my js file i do this:

$.ajax({
  url: "/handler",
  type: "POST",
  dataType: "json",
  data: {"name":"John","location":"Boston"} 
})

and its wrapped inside Drupal.behaviors.mymodule = {...} when I run the ajax, the response I get is an empty array. why don't I receive the data?

  • You've not provided callback function ('handler()') code. You need to debug that and make sure you're receiving values properly (i.e. name, location) and all conditions are matching. This will help you find actual issue. – Yogesh Mar 20 '16 at 9:39
  • I did.. here it is: function handler(){ print_r($_POST); } – H. S. Mar 20 '16 at 9:50
  • Try this, if helps: drupal_json_output($_POST); drupal_exit(); – Yogesh Mar 20 '16 at 9:54
  • thank you but no, it's not working, I get empty json object. – H. S. Mar 20 '16 at 10:29
  • Please edit the question to include the callback and the JavaScript behaviors so we have a more complete view of the code. Also did you rename hook_menu into <module_name>_menu (perhaps post the whole menu hook too)? There are a lot of places where this might go wrong. – Neograph734 Mar 20 '16 at 10:37
0

$_POST is:

An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.

That's not what you're doing. To receive JSON data in PHP you need to use:

$data = json_decode(file_get_contents('php://input'), true);
print_r($data);

Or change the data type of your AJAX request to one of the values that will result in $_POST being populated.

  • HI clive thank you, it's not working, this time i'm getting no answer from the server. no error on the log either. The thing is, the same ajax code is working on a plain php page outside of drupal, but in drupal it's not receiving the data from the client to the server. – H. S. Mar 21 '16 at 9:45

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.