JavaScript post request

Submitted bybarnettech onWed, 03/02/2022 - 15:03
var email = document.querySelector('#edit-investor-profiles-0-entity-field-email-0-value').value;
  if (email.length > 3) {
    // construct an HTTP request
    var xhr = new XMLHttpRequest();
    var url = "/user/register/check-email"
    xhr.open("POST", url, true);
    xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');

    var data = JSON.stringify({"email": email});
    // send the collected data as JSON
    xhr.send(JSON.stringify(data));
    xhr.onreadystatechange = function()
    {
      if (xhr.readyState == 4 && xhr.status == 200)
      {
        var returnedData = xhr.responseText;
        var jsonData = JSON.parse(returnedData);
        if(jsonData['data']['result']) {
          alert("The email you've entered is already in the system, please login to view your advisor matches.");
        }
      }
    }
  }

and the CheckEmail.php controller


email;
    $emailExists = $this->emailExists($email);
    return new JsonResponse(['data' => $emailExists, 'method' => 'GET', 'status' => 200]);
  }

  /**
   * @return array
   */
  public function emailExists($email)
  {
    $ids = \Drupal::entityQuery('user')
      ->condition('mail', $email)
      ->execute();
    $messenger = \Drupal::messenger();
    if (!empty($ids)) {
      $json_array['result'] =  true;
    }
    else {
      $json_array['result'] =  false;
    }
    return $json_array;
  }
}