I really need some help with ajax and jquery

Events happening in the community are now at Drupal community events on www.drupal.org.
twooten's picture

Hello everybody,

I'm sure this is not the right place to post this. It's just that I'm not sure where to post it and I'm about to pull whats left of my hair out messing with this ajax stuff. I have an idea for a niche website and am working to develop it. I want to throw in some ajax and jquery in order to enhance the user experience. So I'm trying to learn how to do things with ajax.

What I am trying to learn is how to allow the user to click on a link or button that will make a database call and get some information to display in a div on the page. Eventually this data will be called from a table that is created by my customized module.

After reading Pro Drupal Development and trying out various code I have been able to write the module and it creates the table. But for testing purposes with this ajax code I have just been using the node table and grabbing the nid and title for the data to display.

Can someone please look at my code and tell me what I need to do to make this work. I want the user to click on a link 'Show Titles', and a list of all node titles will be called from the database and display inside a div. Then every click after that will just call the ajax functions and refresh without a full page reload.

I will attach the code I have so far. The node titles do display on the page inside the div but when I click the link to refresh the page I get some stuff that looks like this:

{ "nodeList": "Site Content Type Setup\x3cbr\x3eRegency Hotel\x3cbr\x3eFirst Shift\x3cbr\x3eHilltop\x3cbr\x3eFirst Shift\x3cbr\x3eSecond Shift\x3cbr\x3eSecond Shift - Regency\x3cbr\x3eWendys\x3cbr\x3eFirst Shift\x3cbr\x3eFirst Shift\x3cbr\x3eHilton Hotel\x3cbr\x3eFirst Shift\x3cbr\x3eJQuery Test\x3cbr\x3eTabs Test\x3cbr\x3etest post\x3cbr\x3edrury\x3cbr\x3efirst shift drury\x3cbr\x3emcdonalds\x3cbr\x3efirst shift - mcdonalds\x3cbr\x3eMirandas Place\x3cbr\x3eFirst shift - Mirandas\x3cbr\x3eTim Wooten\x3cbr\x3eJimmie Officer\x3cbr\x3etest shift\x3cbr\x3eAjax Image Loader\x3cbr\x3eSecond Shift - Mirandas\x3cbr\x3eajax test\x3cbr\x3elist test\x3cbr\x3e" }

Thanks for any help.

Tim

AttachmentSize
scheduler.module.txt2.19 KB
jquery.scheduler.js_.txt393 bytes

Comments

Hi I'm pretty sure this

drupalprojects's picture

Hi

I'm pretty sure this excellent dojo lesson will help you - http://drupaldojo.com/node/73

Thanks for the reply

twooten's picture

I have been through all these tutorials and files. I just can't seem to put the pieces together the way I need to. I've actually just sent an email to joshk pleading for a little help. I downloaded the pastebin text file and am trying to figure that out. I suppose that eventually it will all come together for me.

Tim

Ajax communication

dwees's picture

Hi Tim,

The encoding that is being returned looks a bit wonky. You have URI encoded json data.

To fix it, do the following.

// Suppose the returned text is stored in a variable called returnText. 
// You would add the following line before adding the returned text to the page.
returnText = decodeURIComponent(returnText.replace(/\x/g,'%'));

// now you evaluate the json data to turn it into an array
var myData = eval(returnText);

// now myData['nodeList'] contains the data you want to add to the page

Ajax communication

twooten's picture

Hi dwees,

Thanks for your reply. I hope that eventually this stuff will click in my head and make more sense. I actually sent an email to joshk a little while ago explaining exactly what I am trying to do and the code I am using. I'm gonna copy and paste part of that email here.

Hi Josh,

Man I've been beating my head against my monitor for two days (and
nights!) here trying to understand ajax and jquery. I have posted to the
javascript group at http://groups.drupal.org/node/7281. Got one response
pointing me to stuff I've been digging through for days. So I decided to
ask the guy that seems to know this magic. Watched your Dojo Lesson #12
screencast last night and it was very informative. Between that and the Pro
Drupal Development book I have lots of pieces to the puzzle but just can't
seem to figure out how to put the thing together.

I'll try not to be too long winded here with my explanation. I have an
idea for a website to sell to small companies. Basically what I want to do
is set up the site so that an admin user can schedule his employees for
various shifts at various locations. I'm using cck to create the shifts and
employees, etc. I envision a page with a table or divs for every day of the
week. I call this page 'schedule' and there will be one for each location
that needs to be staffed. I want a button or link on the page that when
clicked will open/show a popup div containing names of all employees. I
want this data to be generated using an ajax call to my employee or user
table. Eventually I would like the user to click on a name, then the div
will go away but the employee will be selected for further processing on
the schedule page.

I have created a module called 'scheduler' and a jquery file called
jquery.scheduler.js as well as a little css file for presentation.
Here is the contents of my module file:

<?php
// $Id$
/
* @file
* scheduler Module.
*/
/

* Implementation of hook_perm().
*/
function scheduler_perm() {
  return array('Show List');
}

/
* Implementation of hook_menu().
*/
function scheduler_menu($may_cache) {
$items = array();
if ($may_cache) {
   $items[] = array(
     'path' => 'schedule/display',
     'callback' => 'scheduler_display',
     'type' => MENU_CALLBACK,
     'access' => user_access('display Schedule'),
   );
}
return $items;
}

/

* Called by jQuery.
*/
function scheduler_display() {
  global $user;
  $nodelist = scheduler_get_list();
  watchdog('scheduler', t('list run by @user accepted', array('@user' => $user->name)));
  // This print statement will return results to jQuery's request.
  print drupal_to_js(array('nodeList' => $nodelist));
  exit();
}

function scheduler_get_list() {
  return db_result(db_query('SELECT title FROM {node} ORDER BY RAND() LIMIT 0,1'));
}

/
* Create node title list widget to display on the page.
*/
function scheduler_jquery_widget() {
  // Load the JavaScript and CSS files.
  drupal_add_js(drupal_get_path('module', 'scheduler') .'/jquery.scheduler.js');
  drupal_add_css(drupal_get_path('module', 'scheduler') .'/scheduler.css');
  global $user;
  $nodeTitles = scheduler_get_list();
  return theme('scheduler_widget', $nodeTitles);
}

function theme_scheduler_widget($nodeTitles) {
  $output = '<div class="scheduler-widget">';
  $output .= '<div class="dolist">';
  $output .= l(t('Show List'), "schedule/display", array('class' => 'scheduler-link'));
  $output .= '</div>';
  $output .= '<div class="nodeList">';
  $output .= $nodeTitles;
  $output .= '</div>';
  $output .= '</div>';
  return $output;
}

/

* Implementation of hook_nodeapi().
*/
function scheduler_nodeapi(&$node, $op, $teaser, $page) {
switch ($op) {
   case 'view':
       $node->content['scheduler_widget'] = array(
           '#value' => scheduler_jquery_widget(),
           '#weight' => 100,
         );
     break;
   case 'delete':
     db_query('DELETE FROM {scheduler} WHERE nid = %d', $node->nid);
     break;
}
}

I'm sure you have read Pro Drupal Development. Most of this code was taken
from the 'Voting Widget'. As you can see I am reading the 'node' table and
just pulling node titles from that table. In the function
theme_scheduler_widget() a link is being created that shows the text 'Show
List'. When it is click, sure enough a random node title displays on the
page inside the 'scheduler-widget' div. But using 'db_result()' only
returns one item at a time. I need to return a list and have it displayed
instead of just the single item.

I have mucked around with the db_fetch_object() but can't seem to get to
where I'm trying to go. I know it should be some form of

while($node = db_fetch_object($result)) {
   $rows = array($node->nid, $node->title);
   $rows[]=$row;
   $output .= $rows[1];
   $output .= '<br>';
}

but passing the array around in the various functions is not working for
me. My jquery file is as follows:

if (Drupal.jsEnabled) {
$(document).ready(function(){
   $('a.scheduler-link').click(function(){
     var listRes = function (data) {
       var result = Drupal.parseJson(data);
       $('div.nodeList').html(result['nodeList']);
     }
     $.get(this.href, null, listRes);
     return false;
   });
});
}

So I'm pretty much at my wits ends here not knowing what to do. I'm not at all afraid of doing the research were, it's just that I don't know where else to look. Any help you can give me would be greatly appreciated.

I was pretty sure that the JSON stuff was "wonky" like you said. But because I don't have much to go on I just copied the code from the Pro Drupal Book. I guess my main problem is in not understanding what the whole 'function(data)' thing is supposed to be doing.

if (Drupal.jsEnabled) {
  $(document).ready(function(){
    $('a.scheduler-link').click(function(){
        var listRes = function (data) {
        returnText = decodeURIComponent(returnText.replace(/\x/g,'%'));
        var myData = eval(returnText);
        var result = Drupal.parseJson(data);
        $('div.nodeList').html(myData['nodeList']);
      }
      $.get(this.href, null, listRes);
      return false;
    });
  });
}

I hope that the email text above better explains where I'm trying to go with this and maybe you can help me get on the right track. Like I said before, I've studied everything I can get my hands on but it's just not clicking with me.

Thanks again for your help and above all patience!

Tim

okay

dwees's picture

The function(data) is what is called an anonymous function in JavaScript, and 'data' is filled with the return data from the server.

So your function should be:

if (Drupal.jsEnabled) {
$(document).ready(function(){
$('a.scheduler-link').click(function(){
var listRes = function (data) {
returnText = decodeURIComponent(data.replace(/\x/g,'%'));  // note the small change here.
var myData = eval(returnText);
var result = Drupal.parseJson(data);
$('div.nodeList').html(myData['nodeList']);
}
$.get(this.href, null, listRes);
return false;
});
});
}

I'm not sure about the SQL stuff though, but hopefully the above helps. I have actually read the Professional Drupal development book, but not recently, and I don't know about the examples in it very well.

Another choice you have is to play around with the 'Dynamic Views' module, which might do what you want.

Dave

Javascript

Group notifications

This group offers an RSS feed. Or subscribe to these personalized, sitewide feeds:

Hot content this week