How to handle form submission using AJAX in Drupal 8

Here is the buildForm function for creating an AJAX form.

  public function buildForm(array $form, FormStateInterface $form_state) {
  
    $form = [];
    $form['email'] = [
      '#type' => 'textfield', 
      '#attributes' => ['placeholder'=>'Enter your Email ID'],
      '#description' => 'Submit your email address to recieve updates',
      '#size' => 100,
      '#maxlength' => 150,
      '#required' => TRUE,  
    ];

    $form['submit_button'] = [
      '#type' => 'submit',
      '#name' => 'submit-email',
      '#value' => '>',
      '#ajax' => [
        'callback' => '::processEmail',
        'wrapper' => 'thanks-message',
        'effect' => 'fade',
        'event' => 'click',
        'progress' => [
          'type' => 'throbber',
          'message' => $this->t('Processing ...'),
        ],
      ],
    ];

    $form['thanks'] = [
     '#type' => '#markup',
     '#markup'=> '',
     '#prefix' => '<div id="thanks-message">',
     '#suffix' => '</div>'
    ];

    $form['error'] = [
     '#type' => '#markup',
     '#markup'=> '',
     '#prefix' => '<div id="error-message">',
     '#suffix' => '</div>'
   ];

    return $form;
  }

And this the code for callback function.

  public function processEmail (array &$form, FormStateInterface $form_state) {
    $form['#cache'] = ['max-age' => 0];
    $email = $form_state->getValue('email');
    $renderer = \Drupal::service('renderer');
    $response = new AjaxResponse();

    if (!(\Drupal::service('email.validator')->isValid($email))) {
      $elem = [
        '#type' => 'markup',
        '#markup'=> 'Please provide correct Email ID',
        '#prefix' => '<div id="error-message">',
        '#suffix' => '</div>'
      ];
      $response->addCommand(new InsertCommand('#error-message', $renderer->render($elem)));
      return $response;
    }
    else {
      $element = [
        '#type' => 'markup',
        '#markup'=> 'Thank you! Please check your email for confirmation message.',
        '#prefix' => '<div id="thanks-message">',
        '#suffix' => '</div>'
      ];

      $error = [
        '#type' => 'markup',
        '#markup'=> '',
        '#prefix' => '<div id="error-message">',
        '#suffix' => '</div>'
      ];

      //$elma used as an empty variable to hide unwanted element.s

      $response->addCommand(new ReplaceCommand('#thanks-message', $renderer->render($element)));
      $response->addCommand(new ReplaceCommand('#edit-submit-button', $renderer->render($elema)));
      $response->addCommand(new ReplaceCommand('#edit-email--description', $renderer->render($elema)));
      $response->addCommand(new ReplaceCommand('#edit-email', $renderer->render($elema)));
      $response->addCommand(new RemoveCommand('#error-message'));
      return $response;
    }
  }