tags:

views:

480

answers:

2

I'm looking to create a drupal node with javascript, from the same site, and I wonder which direction I should go.

I know you can use services/json to do this, but surely there's a simpler way?

Thanks

A: 

The first place I'd look would be here:

http://docs.jquery.com/Ajax

And proceed to the load() function first

http://docs.jquery.com/Ajax/load#urldatacallback

to see if that's enough for your needs.

Start with the simplest form of Ajax call that you may need,it's easy to become bogged down in the complexity of the more universal $.ajax()

+2  A: 

Besides an AJAX callback, you'll probably need to have a menu callback in Drupal that will take the AJAX request and turn it into a node object and save it with node_save.

In its simplest form, it'd look something like this (beware that there's no access checking here, so anyone can create a node using this callback):

<?php
/**
 * Implementation of hook_menu().
 */
function demo_menu() {
  $items = array();
  $items['demo/js'] = array(
    'title' => 'Demo page',
    'page callback' => 'demo_js_page',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Page callback that saves a node.
 */
function demo_js_page() {
  if (isset($_REQUEST['title'])) {
    $node = new stdClass;
    $node->type = 'blog';
    $node->title = check_plain($_REQUEST['title']);
    node_save($node);
    drupal_set_message(t('Created node %title', array('%title' => $_REQUEST['title'])));
  }
  return t('Thanks for visiting');
}

The code shown is from to be inserted into a demo.module file in a folder like sites/all/modules/demo on your Drupal site. You'll also need a demo.info file looking a bit like this:

name = Demo module
description = Demo code.
core = 6.x
mikl
Note that a good number of node modules not written too well won't work with just that code. Also, even when this works, you'll probably want to preprocess the node with node_prepare before node_save, to apply the content filter, which the code you give doesn't do.
FGM
Yeah, only adding a title to the new node might not be the most common use case. My code example is probably better described as the bare minimum :)
mikl