WebTechKitchen; Your Web Technology Kitchen, contact us to create, or maintain your websites and other digital properties.

Ajax calls in Drupal

Submitted by barnettech on Fri, 05/06/2022 - 10:29

To send the json data in JavaScript

   var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance
   xmlhttp.open("POST", "/user/17352/post-dashboard");
   xmlhttp.setRequestHeader("Content-Type", "application/json");
   xmlhttp.send(JSON.stringify({advisorcomment:advisorComment}));

To receive the json data in PHP

 $json_string = \Drupal::request()->getContent();
    $decoded = \Drupal\Component\Serialization\Json::decode($json_string);
    print_r($decoded);
    $name = $decoded['name'];

    return new JsonResponse($name);