A
A
Andrey Shumilin2018-02-23 23:40:27
JavaScript
Andrey Shumilin, 2018-02-23 23:40:27

Why doesn't the AJAX request work?

Recently I made such a site ul-massage.ru . I started setting up the form for sending an application for a service (so far only using the form in the Contacts section as an example). Letters with the data received from the form come to the mail only if I include the mail.php file through the action:

<form  class="contact_form" action="mail.php" novalidate target="_blank" method="post"></form>


Here is the complete form code:
<form  class="contact_form" action="mail.php" novalidate target="_blank" method="post">
            <h3>Оставить заявку</h3>
            
            <input type="hidden" name="project_name" value="ul-massage.ru">
                    <input type="hidden" name="admin_email" value="[email protected]">
                    <input type="hidden" name="form_subject" value="Лендинг по массажу - заявка на массаж">

            <label class="form-group">
              <span>Ваше имя:</span> <br>
              <input type="text" name="Имя клиента" placeholder="Ваше ФИО..." data-validation-required-message="Вы не ввели имя" required>
              <span class="help-block text-danger"></span>
            </label>

            <label class="form-group">
              <span>Ваш телефон:</span> <br>
              <input type="tel" name="Телефон" placeholder="Ваш телефон..." data-validation-required-message="Не корректно введен телефон" required>
              <span class="help-block text-danger"></span>
            </label>

            <label class="form-group">
              <span>Дата записи:</span> <br>
              <input type="datetime-local" name="Дата записи" id = "datetime" data-validation-required-message="Не выбрана дата записи" value="2018-01-01T08:30" required>
              <span class="help-block text-danger"></span>
            </label>

            <label class="form-group">
              <span>Выберите услугу:</span> <br>
              <select name="Услуга">
                <option value="Массаж головы">Массаж головы</option>
                <option value="Антицеллюлитный массаж">Антицеллюлитный массаж</option>
                <option value="Массаж грудной клетки">Массаж грудной клетки</option>
                <option value="Массаж верхних конечностей">Массаж верхних конечностей</option>
                <option value="Массаж нижних конечностей">Массаж нижних конечностей</option>
                <option value="Массаж лица">Массаж лица</option>
                <option value="Массаж шейно-воротниковой зоны">Массаж шейно-воротниковой зоны</option>
                <option value="Массаж спины">Массаж спины</option>
                <!--<option value="Вакуумный массаж">Вакуумный массаж</option> -->
                <option value="Детский массаж">Детский массаж</option>
                <option value="Классический массаж">Классический массаж</option>
                <option value="Расслабляющий массаж<">Расслабляющий массаж</option>
              </select>
              <span class="help-block text-danger"></span>
            </label>

            <button class="button button-green">Записаться на прием</button>

          </form>


This opens a new tab named mail.php. When trying to send data via ajax request, emails are not sent at all. What could be the problem?

mail.php file:

<?php

$method = $_SERVER['REQUEST_METHOD'];

//Script Foreach
$c = true;
if ( $method === 'POST' ) {

  $project_name = trim($_POST["project_name"]);
  $admin_email  = trim($_POST["admin_email"]);
  $form_subject = trim($_POST["form_subject"]);

  foreach ( $_POST as $key => $value ) {
    if ( $value != "" && $key != "project_name" && $key != "admin_email" && $key != "form_subject" ) {
      $message .= "
      " . ( ($c = !$c) ? '<tr>':'<tr style="background-color: #f8f8f8;">' ) . "
      <td style='padding: 10px; border: #e9e9e9 1px solid;'><b>$key</b></td>
      <td style='padding: 10px; border: #e9e9e9 1px solid;'>$value</td>
    </tr>
    ";
  }
}
} else if ( $method === 'GET' ) {

  $project_name = trim($_GET["project_name"]);
  $admin_email  = trim($_GET["admin_email"]);
  $form_subject = trim($_GET["form_subject"]);

  foreach ( $_GET as $key => $value ) {
    if ( $value != "" && $key != "project_name" && $key != "admin_email" && $key != "form_subject" ) {
      $message .= "
      " . ( ($c = !$c) ? '<tr>':'<tr style="background-color: #f8f8f8;">' ) . "
      <td style='padding: 10px; border: #e9e9e9 1px solid;'><b>$key</b></td>
      <td style='padding: 10px; border: #e9e9e9 1px solid;'>$value</td>
    </tr>
    ";
  }
}
}

$message = "<table style='width: 100%;'>$message</table>";

function adopt($text) {
  return '=?UTF-8?B?'.Base64_encode($text).'?=';
}

$headers = "MIME-Version: 1.0" . PHP_EOL .
"Content-Type: text/html; charset=utf-8" . PHP_EOL .
'From: '.adopt($project_name).' <'.$admin_email.'>' . PHP_EOL .
'Reply-To: '.$admin_email.'' . PHP_EOL;

mail($admin_email, adopt($form_subject), $message, $headers );


The ajax request itself:

$("form .contact_form").submit(function() { //Change
    var th = $(this);
    $.ajax({
      type: "POST",
      url: "/mail.php", //Change
      data: th.serialize()
    }).done(function() {
      alert("Thank you!");
      setTimeout(function() {
        // Done Functions
        th.trigger("reset");
      }, 1000);
    });
    return false;
  });

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question