Tuesday, October 22, 2013

Drupal - Post Data via Ajax to PHP Menu Callback with JQuery and JSON

Put this PHP code inside your module, e.g. sites/all/modules/my_module/my_module.module
drupal_add_js(drupal_get_path("module","my_module") . "/my_module.js");

function my_module_perm () {
  return array(
    'access my_module via ajax',
  );
}

function my_module_menu () {
 
  $items = array();
 
  $items['my_module/example'] = array(
    'page callback' => 'my_module_example',
    'access arguments' => array('access my_module via ajax'),
    'type' => MENU_CALLBACK,
  );
 
  return $items;
}

function my_module_example () {
  if (empty($_POST["js"])){ die(); }
  $result = array('msg' => 'my_module_example - hello from php','valid' => true);
  drupal_json($result);
  exit();
}

Put this Javascript code inside your module's javascript file, e.g. sites/all/modules/my_module/my_module.js
if (Drupal.jsEnabled) {
$(document).ready(function () {
  
   
  // ajax return
  var my_module_example = function (data) {
    alert(data.msg);
  }
    
  // ajax call
  $.ajax({
    type: 'POST',
    url: Drupal.settings.basePath + 'my_module/example',
    dataType: 'json',
    success: my_module_example,
   data: 'js=1&my_module_post_data=2012'
  });

});
}
Don't forget to clear Drupal's menu cache and grant permissions to your users to be able to access the menu callback url.