• Home
  • New Entries
  • Popular Entries
  • Submit a Story
  • About

Dispatching AJAX requests with Drupal and JSON ...

1 :: Heed MENU_CALLBACK! One of the frequently overlooked capabilities of Drupal is the so-called MENU_CALLBACK. Strangely, this straightforward menu-item type is among the unpopular ones. MENU_CALLBACK is simple. It only indicates that your defined path will be wired to some callback function in your module. Let's see how this works:

View More Info

<?php
                function mymodule_menu($may_cache) {
                    if (!$may_cache) {
                        $items[] = array(    path => json/dispatcher,
                                            itle    => t(Dispatcher of Ajax Requests),
                                            callback => amymodule_dispatcher,
                                            access => true,
                                            ype => MENU_CALLBACK
                        );
                    }
                  
                    return $items;
                }
          
?>

The above snippet maps the path website.com/json/dispatcher to the function mymodule_dispatcher(). Everything that comes after the path will be passed into the function as parameters. For example if we used this URL: website.com/json/dispatcher/hello/world, and defined the function like this: function mymodule_dispatcher($var1, $var2) - then in the function $var1 would equal hello, and $var2 → world respectively. This callback functionality is exactly what we need to create an AJAX+JSON event dispatcher.
2 :: Possibilities with callback function.

The trick to writing callback functions ( mymodule_dispatcher() in our case ) is in knowing the Drupal is framework. Commonly, Drupal is considered to be a CMS (Content Management System). Only when looking deeper, one would uncover the well-designed, powerful framework which makes all the surface functionality possible. If Drupal was a bicycle factory, and you were an engineer working on imroving the bicycles - you would be allowed to redirect the product into your own conveyer belt at any points during production. You could let the factory build the bicycle frame, then redirect it to your own conveyer belt to make your additions/alterations, after which you could let it back into regular production.

Alright, I am getting a little ahead of myself there. In our module we will talk back to the client using drupal_to_js() function. This function accepts either an associative array or an object, and returns well-cooked JSON.

<?php
                $object = new stdClass();
                $object->var1 = hello;
                $object->var2 = world;
                $object->var3 = array( 1 => fluffy, 2 => horse );
                echo drupal_to_js($object);
          
?>

This snippet would output valid JSON, which is easily parsable by javascript.
3 :: Designing our dispatcher.

Dispatcher is there to dispatch. Let is follow the KISS principle and use PHP is switch() control statement.

<?php
                function mymodule_dispatcher($action) {
                    $out = new stdClass();
                    switch ($action) {
                        case aregister:
                            // handle registration, write output to $out
                        break;
                        case login:
                            // handle login, write output to $out
                        break;
                        default:
                            // handle nothing
                        break;
                    }
                  
                    header("Content-type: application/json");
                    echo drupal_to_js($out);
                }
          
?>

With this simple dispatcher we can accept any URL such as website.com/json/dispatcher/[anything], and most importantly, nobody stops us from POSTing values into that URL. This means we can use Drupal is framework, and talk directly to client (bypassing theming). Javascript developer would only have to post values to your dispatcher, and work with returned JSON. Lets expand the function a little bit, using the login/register example.

<?php
                function mymodule_dispatcher($action) {
                    $out = new stdClass();
                    switch ($action) {
                        case aregister:
                            $out->messages = ;
                            // assuming _nick_available() function is written elsewhere in the module
                            if ( !_nick_available($_POST[ ame]) ) {
                                $out->messages = array( ame => This username is already taken.);
                                break;
                            }
                          
                            // this will process our POSTed values as if they were from Drupal is register form
                            drupal_execute(user_register, $_POST);
                            if ( $errors = form_get_errors() ) {
                                $out->messages = $errors;
                            }
                        break;
                      
                        case login:
                            global $user;
                            $out->messages = ;
                          
                            if ( !($user->uid > 0) )
                                $user = user_authenticate( $_POST[user], $_POST[pass] );
                          
                            if ( !($user->uid > 0) )
                                $out->messages = authentication failed;
                        break;
                        case logout:
source: mediumexposure
                            user_logout();
                            $out->messages = ok;
                        break;
                      
                        default:
                            // handle nothing
                        break;
                    }
                  
                    drupal_get_messages(null, true); // this will clear drupal is message buffer
                    header("Content-type: application/json");
                    echo drupal_to_js($out);
                }
          
?>

As you can see - in the above example I used such Drupal framework is functions as drupal_execute(), form_get_errors(), user_authenticate(), and drupal_get_messages(). It shows once again that the hardest part about writing callbacks is in knowing which Drupal is functions to use to achieve the desired effect (without reinventing the bicycle).

 View Full Story.
Posted at 10:14:14 am | Permalink | Posted in JSON  

Related Stuff

  • MooV: Using cutting edge Video phones and Software Video Phones - coupling all that with VoIP and empowering the disabled.

  • Moo Telecom: VoIP communications made easy - Ring anyway with the fun and ease of using a normal phone

  • TagR:Mobile Social Network with Real Time Locations Based services, and Ambience Intelligence, VoiP, IM, Skype, Googletalk, Mapping, Flickr, Events, Calendaring, Scheduling, SecondLife Support

  • ClearSMS : ClearSMS is a Web-based application that lets you send bulk SMS messages to your customers, contacts, or just about anyone.

  • Jajah:jah is a VoIP (Voice over IP) provider, founded by Austrians Roman Scharf and Daniel Mattes in 2005[1]. The Jajah headquarters are located in Mountain View, CA, USA, and Luxembourg. Jajah maintains a development centre in Israel.

  • Skype: It’s free to download and free to call other people on Skype. Skype the number one voice over ip software

  • PrivatePhone: a free local phone number with voicemail and messages you can check online or from any phone.

Be the first ... |Add your comment.

Your Comment ...

  Name (required)

  Email (required, hidden)

  Website


About Ajaxlines

Ajaxlines is a project focused on providing its audience with a database of most of Ajax related articles, resources, tutorials and services from around the world.

Its purpose is to showcase the power of Ajax and to act as a portal to the Ajax development community.


Recent Stuff

Using ASP.NET AJAX JSON Asynchronous Web Services

Growl for Windows and a Web Notification API

Learn AJAX from Scratch - Part II

Learn AJAX from Scratch - Part I

PHP AJAX CHAT, Bug fixes - including weird mozilla bug

Learn PHP From Scratch


Our Partners

Ajax Projects

Web 2.0 Sites

Webloglines

Human Development Handbook

Software Development Company

Ajaxlines


Search


Topics

  • .Net (96)
  • Articles (76)
  • Bookmarking (35)
  • Calendar (18)
  • Chat (38)
  • ColdFusion (3)
  • CSS (30)
  • Email (23)
  • Flash (13)
  • Games (6)
  • Google (17)
  • Html (6)
  • Image (11)
  • International Calls & VOIP (7)
  • Java (34)
  • Javascript (146)
  • JSON (16)
  • Perl (2)
  • PHP (82)
  • Presentation (19)
  • Python (3)
  • Resources (1)
  • RSS (1)
  • Ruby (7)
  • Storage (4)
  • Toolkits (87)
  • Tutorials (190)
  • UI (11)
  • Utilities (161)
  • Web2.0 (13)
  • XmlHttpRequest (18)
  • YUI (4)

© 2006 www.ajaxlines.com. All Rights Reserved. Powered by IRange