Drupal 8 href link assigning callback action - ajax

by Mo-ster   Last Updated November 12, 2017 18:07 PM

I have a situation where I would like to define a href link and when it is clicked, for it to trigger an ajax response such as sending back some information which can then be shown on the page...

Part 1. Creating the link... So I've created the link via:

    $url = Url::fromUserInput('#');

    $nxt_button=Link::fromTextAndUrl('Submit Application',$url);

    $nxt_button['#attributes'] = [



Now in the '#attributes' I assume i could put something like 'callback' => 'name of function to be run' ... but, if the function to be run resides in another object say 'ajax_test_script.php' how would I do that?

Part 2. Say the server side responding code, was in a different class called 'ajax_test_scirpt' and the function to call is 'start' ... If I was sending back information via:

$response=new AjaxResponse();
$response->addCommand(<<what goes here>>);
return $response;

And these lines of code were inside the function 'start'... What would I put as the input parameter for addCommand, if I wanted the response to behave such that it could call the javascript function outlined below, which would be attached to the page (e.g call readMessage passing in the parameters needed by the readMessage function):

(function($, Drupal) {
 * Add new command for reading a message.
Drupal.AjaxCommands.prototype.readMessage = function(ajax, response, status){
    // Place content in current-msg div.
    $('#current-msg h2').html(response.subject);
    $('#current-msg p').html(response.content);
    // Remove from unread list.
    $('#msg-' + response.mid).remove();
    // Add message to read list.
    $('#read-msgs').append('<li>' + response.subject + '</li>');

})(jQuery, Drupal);

Any help is appreciated.

Tags : 8 ajax

Related Questions

Decoding cyrillic %get[] parameter in Ajax form

Updated June 11, 2015 08:03 AM

How to reload Google chart on ajax submit?

Updated August 12, 2015 17:03 PM

grab and reuse AJAX request parameters in a view

Updated July 17, 2015 13:03 PM