5

First I am not very good in JavaScript so maybe I do not know some very basics... I apologize in advance.

I created a form where I want to save every change in single fields directly without the need to submit the form each time. Therefore I created a custom route which returns an AjaxResponse on successfull database savings as well as on any errors on the Drupal side.

But I want to be aware of any errors which may appear on the client side as well. $.ajax() has the function .fail() and .done() where I can do different things in my JavaScript when something went wrong. These methods are missing for Drupal.ajax(). Is there any way to react on errors when using Drupal.ajax()?

I tried

try {
  Drupal.ajax({url: path}).execute();
}
catch (e) {
  alert(e.name + ": " + e.message);
}

and built in some errors on my controller but all that happens is that the browsers console lists Ajax errors - no alert is shown to the client.

8

You can using like jQuery ajax. Because Drupal.ajax({}).execute() is a function and return the jqXHR.

 /**
   * Execute the ajax request.
   *
   * Allows developers to execute an Ajax request manually without specifying
   * an event to respond to.
   *
   * @return {object}
   *   Returns the jQuery.Deferred object underlying the Ajax request. If
   *   pre-serialization fails, the Deferred will be returned in the rejected
   *   state.
   */
  Drupal.Ajax.prototype.execute = function() {
    // Do not perform another ajax command if one is already in progress.
    if (this.ajaxing) {
      return;
    }

    try {
      this.beforeSerialize(this.element, this.options);
      // Return the jqXHR so that external code can hook into the Deferred API.
      return $.ajax(this.options);
    } catch (e) {
      // Unset the ajax.ajaxing flag here because it won't be unset during
      // the complete response.
      this.ajaxing = false;
      window.alert(
        `An error occurred while attempting to process ${this.options.url}: ${e.message}`,
      );
      // For consistency, return a rejected Deferred (i.e., jqXHR's superclass)
      // so that calling code can take appropriate action.
      return $.Deferred().reject();
    }
  };

source

So in your case:

var ajaxExecute = Drupal.ajax({url: path}).execute();

ajaxExecute.done(function() {
    alert( "success" );
})
.fail(function() {
    alert( "error" );
})
1

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.