J
J
Junior Development2020-04-23 19:18:34
PHP
Junior Development, 2020-04-23 19:18:34

When sending to ajax/php mail, empty fields are received. What is the reason?

When sent to the mail, the notification comes and everything is fine, but after ajax connection, empty fields come.
Please tell me what is the reason?

<form action="server.php" class="order-form main-form" id="form" method="post" name="user_form">
      <input type="text" placeholder="Имя и фамилия" name="name" required="required">
      <input type="email" placeholder="E-mail" name="email" required="required">
      <input type="tel" placeholder="Телефон" name="phone" required="required">
      <button class="button btn form-btn" id="submit_btn" type="submit">Оставить заявку!</button>
  </form>

$post_data = $_POST;
$to = '[email protected]';
$subject = 'Заявка с лендинга';
$message = 'Заявка с лендинга<br />
Имя: ' . $post_data['name'] . '<br />
E-mail: ' . $post_data['email'] . '<br />
Телефон: ' . $post_data['phone'];
$headers = "MIME-Version: 1.0\r\n" . "Content-type: text/html; charset=utf-8\r\n" . "From: <[email protected]>\r\n";
mail ($to, $subject, $message, iconv ('utf-8', 'windows-1251', $headers));

/* Всплывающее сповещение  */
      const errorMesage = 'Что-то пошло не так...';
      const loadMesage = 'Загрузка...';
      const successMesage = 'Спасибо! Мы скоро с Вами свяжемся!';

     /* Стилизация сообщения*/
     const statusMessage = document.createElement('div');
     statusMessage.style.cssText = `font-size: 2rem; color: #fff`;

      /* Очищаем input при отправке */
      const clearInput = () => {
        const inputs = document.querySelectorAll('input');
        inputs.forEach((item, i, arr) => {
          inputs[i].value = '';
        });
      };


      /* form  --------------------------------------------- */
      const form = document.getElementById('form');

      form.addEventListener('submit', (event) => {
        event.preventDefault();

        /*Показываем сообщение и очищаем поля*/
        form.appendChild(statusMessage);
        statusMessage.textContent = loadMesage;
        clearInput();

        const formData = new FormData(form);
        let body = {};
        formData.forEach((val, key) => {
          body[key] = val;
        });

        postData(body, () => {
          statusMessage.textContent = successMesage;
        }, (error) => {
          statusMessage.textContent = errorMesage;
          console.error(error);
        });

      });

      /* ---------------------------------------------- */

      const postData = (body, outputData, errorData) => {

        const request = new XMLHttpRequest();

        request.addEventListener('readystatechange', () => {

          if (request.readyState !== 4) {
            return;
          }
          if (request.status === 200) {
            outputData();
          }else{
            errorData(request.status);
          }
        });

        request.open('POST', './server.php');
        request.setRequestHeader('Content-Type', 'application/json');
        request.send(JSON.stringify(body));
      };

    };

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Romantsov, 2020-04-24
@romancov_vladimir

Apparently the form is cleaned before the data is taken from it.
Try like this:

postData(body, () => {
        clearInput(); 
        statusMessage.textContent = successMesage;
    }, (error) => {
        statusMessage.textContent = errorMesage;
        console.error(error);
    });

Thus, in case of an error, the user will not have to re-enter everything

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question