Saturday, May 9, 2015

Pass JSON To Drupal Page

I worked on a complex javascript application that comprised of many checkboxes, textfields, dropdowns and multiple steps. The data needed to be stored in a database and since I didn't use Drupal's Ajax, I needed to pass the data asynchronously elsewhere for that to be handled.


This tutorial assumes that you already know how to create a module, so I won't cover that. 

First, let's define the page that will save our data.

/**
 * Implements hook_menu()
 */
function my_custom_module_menu() {
  $items = array();
 
  $items['my_custom_module/json/save/%'] = array(
    'title' => 'Save JSON Data',
    'page callback' => 'my_custom_module_json_save',
    'page arguments' => array(3),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

"my_custom_module/json/save" is the page we'll be calling to. The "%" in the url is a wildcard for a parameter, which in this case will be our JSON object. The value for page callback will be the function that is executed when that page is hit. Let's define that below.
function my_custom_module_json_save($json) {
  $data = json_encode($json); // Converts the string into an object
  // Insert data into database
}

The above function is obviously incomplete. You'll need to implement one of Drupal's DB functions such as db_insert to store the data in the database.

Finally, let's create the javascript that passes the string converted object to our Drupal page. Note, jQuery is used for the ajax request.


And that's it! Please, leave a comment if you need further help or clarification.

No comments:

Post a Comment