@Nub_Ready
Начинающий Front-end разработчик Опыт >6 месяцев

Не работает Ajax запрос при отправке формы обратной формы. В чем причина?

Подключил небольшой Ajax скрипт в связке SMTP - отправкой данных с формы, но при отправке страница перезагружается и выходит пустой экран.

html код формы:
<form action="mailer/smart.php" method="POST" class="wrap-form">
          <div class="wrap-input">
             <input type="text"  name="user_name" placeholder="введите ваше имя">
            <input type="tel" name="user_phone" placeholder="ваш номер телефона">
          </div>
          <div class="wrap-button">
             <button class="btn blik" type="submit">перезвоните мне</button>
          </div>
         </form>


Код ajax-скрипта:

$('form').submit(function(event) {
    event.preventDefault();
    $.ajax({
      type: "POST",
      url: "mailer/smart.php",
      data: $(this).serialize()
    }).done(function() {
      $(this).find("input").val("");
      alert("Сообщение успешно отправлено");
      $("form").trigger("reset");
    });
    return false;
  });


Код mailer'а:

<?php 

$name = $_POST['user_name'];
$phone = $_POST['user_phone'];

require_once('phpmailer/PHPMailerAutoload.php');
$mail = new PHPMailer;
$mail->CharSet = 'utf-8';

//$mail->SMTPDebug = 3;                               // Enable verbose debug output

$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'smtp.yandex.ru';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = 'lending.sch@yandex.ru';                 // Наш логин
$mail->Password = 'qwerty34';                           // Наш пароль от ящика
$mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465;                                    // TCP port to connect to
 
$mail->setFrom('lending.sch@yandex.ru', 'Школа Немецкого Языка');   // От кого письмо 
$mail->addAddress('kurbatov299@yandex.ru');     // Add a recipient
$mail->isHTML(true);       // Set email format to HTML
$mail->Subject = 'Заявка  на пробный урок';
$mail->Body    = 'Пользователь оставил свои данные <br> Имя: ' . $name . ' <br>Телефон: ' . $phone . '';

if(!$mail->send()) {
    return false;
} else {
    return true;
}

?>
  • Вопрос задан
  • 1176 просмотров
Решения вопроса 1
@Nub_Ready Автор вопроса
Начинающий Front-end разработчик Опыт >6 месяцев
Подключил Jquery в начале документа
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>Заголовок </title>
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="css/normalize.css">
    <link rel="stylesheet" href="css/font-awesome.min.css">
    <link rel="stylesheet" href="css/animate.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 
  </head>


А сам скрипт в конце документа:
<script src="js/jquery.nicescroll.min.js"></script>
    <script src="js/wow.min.js"></script>
    <script src="js/main.js"></script> // ВОТ ОН
    <script>
      new WOW().init();
    </script>
    <script>
      $(document).ready(
          function() {
              $("html").niceScroll({cursorcolor:"#000"});
          }
      );
    </script>
  </body>
</html>

Сам скрипт выглядит так: c
$(function(){
$('form').submit(function(event) {
    event.preventDefault();
    $.ajax({
      type: "POST",
      url: "mailer/smart.php",
      data: $(this).serialize()
    }).done(function() {
      $(this).find("input").val("");
      alert("Сообщение успешно отправлено");
      $("form").trigger("reset");
    });
    return false;
  });
});


Страница по прежнему перезагружается и выходит белый экран
Ответ написан
Пригласить эксперта
Ответы на вопрос 3
ThunderCat
@ThunderCat Куратор тега PHP
{PHP, MySql, HTML, JS, CSS} developer
$(function(){
$('form').submit(function(event) {
    event.preventDefault();
   let that = $(this);
    $.ajax({
      type: "POST",
      url: "mailer/smart.php",
      data: that.serialize()
    }).done(function() {
      that.find("input").val("");
      alert("Сообщение успешно отправлено");
      that.trigger("reset");
    });
    return false;
  });
})
Ответ написан
gzhegow
@gzhegow
aka "ОбнимиБизнесмена"
Может ты скрипт свой вешаешь на onSubmit еще до того как загрузилась jquery у которого async?
Ответ написан
@FKV
Подключи jQuery до скрипта с отправкой и оберни его в
$(document).ready(function (){
Твой код
});
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы