1

I've got a custom AJAX link on my site, which does it's current job fine, but what I'd like to do is make it change the href attribute of an element on the page as well. I'm not brilliant at jQuery, so I'm not sure how I'd use the Drupal AJAX commands to do something like this, if it can even be done.

Basic info of my existing setup

HTML

<a href="path/to/my/site/ajax/mymodule/slide/15" class="use-ajax ajax-processed">Add</a>

Module

/**
 * Implements hook_menu().
 */
function mymodule_menu() {
    // Creates a page to listen for a new slide being added
    $items['ajax/mymodule/slide/%node'] = array(
        'page callback' => 'mymodule_append_slide_to_deck',
        'page arguments' => array(3),
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
    );

  return $items;
}

function mymodule_append_slide_to_deck($node) {
    if (!empty($node)) {
        if ($node->field_image) {
            // CODE TO GET HTML OF THUMBNAIL FROM THE NODE REFERENCED, ADDED TO VAR $thumbnail

            // Prepare an ajax command to insert the node html into our ajax wrapper.
            $commands = array();
            $commands[] = ajax_command_append('#deck .deck-creator', $thumbnail);

            // Render the commands into JSON and print them.
            print ajax_render($commands);
            exit;
        }
    }
}

All this part works fine, does it's job. However I have another button on the page, and I'd like to pass this Node ID of the node I've referenced (in this case 15) to the end of the href property. Can this be done? or is the simplest thing to replace the HTML entirely using ajax_command_replace();?

1

Found the best way of doing this was using ajax_command_invoke() instead.

By using this you can make a call to a custom jQuery function, in which you can then do what you want.

    ...
    // Prepare an ajax command to insert the node html into our ajax wrapper.
    $commands = array();
    $commands[] = ajax_command_html('#deck .deck-creator', $thumbnails);
    $commands[] = ajax_command_invoke(NULL, array('customAction'));

in a jQuery file

(function($) {
    $.fn.customAction = function() {
        // do my code
    }
})(jQuery);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.