Skip to main content

Json

Displaying 1 - 4 of 4

Sending JSON with Basic Authentication Credentials

To post JSON to a server with Basic Authentication credentials, you need to make an HTTP POST or PUT request, include the JSON in the body of the HTTP message, and pass the "Authorization: Basic [token]" HTTP header to the server. 
The [token] is a Base64 encoded string of user credentials in the form of a login:password string. 
In this POST JSON with a Basic Authentication Credentials Example, we send a POST request with JSON body and "Authorization: Basic [token]" header to the ReqBin echo URL. 

<script>
      var USERNAME="admi";
      var PASSWORD="chanud";

      var person = {
        firstName:"tester2",
        lastName:"drupal",
        userName:"tester2drupal",
        eMail:"teter2@drupalvip.com",
        pass1:"teter2drupal",
        passConfirm:"teter2drupal",
        role:"Affiliate" 
      };
      
      $.ajax({
        type: "POST",
        url: 'https://mydomain/api/route',
        dataType: 'json',
        headers: {
         "Authorization": "Basic " + btoa(USERNAME + ":" + PASSWORD)
        },
        data: person,
        //data: JSON.stringify(person),
        success: function (data) {
          $("response").html(data.msg);
        },                
      });
    </script>

Custom controller with JSON response

how to create a custom controller with JSON response in Drupal 8.

this might work on Drupal 9 and 10, but I never tested it on these versions.

use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * Class JsonApiArticlesController
 * @package Drupal\mymodule\Controller
 */
class JsonApiArticlesController {

  /**
   * @return JsonResponse
   */
  public function index() {
    return new JsonResponse([ 'data' => $this->getData(), 'method' => 'GET', 'status'=> 200]);
  }

  /**
   * @return array
   */
  public function getData() {

    $result=[];
    $query = \Drupal::entityQuery('node')
      ->condition('type', 'article')
      ->sort('title', 'DESC');
    $nodes_ids = $query->execute();
    if ($nodes_ids) {
      foreach ($nodes_ids as $node_id) {
        $node = \Drupal\node\Entity\Node::load($node_id);
        $result[] = [
          "id" => $node->id(),
          "title" => $node->getTitle(),
        ];
      }
    }
    return $result;
  }
}
use Symfony\Component\HttpFoundation\JsonResponse;

// if you know the data to send when creating the response
$response = new JsonResponse(['data' => 123]);

// if you don't know the data to send or if you want to customize the encoding options
$response = new JsonResponse();
// ...
// configure any custom encoding options (if needed, it must be called before "setData()")
//$response->setEncodingOptions(JsonResponse::DEFAULT_ENCODING_OPTIONS | \JSON_PRESERVE_ZERO_FRACTION);
$response->setData(['data' => 123]);

// if the data to send is already encoded in JSON
$response = JsonResponse::fromJsonString('{ "data": 123 }');

Display Forms in a Modal Dialog

Display create a node in a modal dialog

By default when creating a node, the save action will redirect the user to another page but if we want to just close the modal dialog and leave the user on the same page we need to tell the form to do that.

For this we are going to alter the form and add an AJAX command letting Drupal know that we want to close the dialog as soon as the node is created.

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\CloseModalDialogCommand;
use Drupal\Core\Ajax\RedirectCommand;

/**
 * Implements hook_form_alter().
 */
function modal_form_example_form_node_article_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['actions']['submit']['#submit'][] = '_modal_form_example_ajax_submit';
  $form['actions']['submit']['#attributes']['class'][] = 'use-ajax-submit';
  // in some cases this was needed:
  // $form['#attached']['library'][] = 'core/jquery.form';
  // $form['#attached']['library'][] = 'core/drupal.ajax';
}

/**
 * Close the Modal and redirect the user to the homepage.
 *
 * @param array $form
 *   The form that will be altered.
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 *   FormState Object.
 */
function _modal_form_example_ajax_submit(array $form, FormStateInterface &$form_state) {
  $response = new AjaxResponse();
  $response->addCommand(new CloseModalDialogCommand());
  $form_state->setResponse($response);
}