A
A
Alexander Kurbatov2019-08-24 01:01:14
PHP
Alexander Kurbatov, 2019-08-24 01:01:14

Ajax request does not work when submitting a form back form. What is the reason?

I connected a small Ajax script in the SMTP bundle - sending data from the form, but when submitting, the page reloads and a blank screen comes out.

html form code:

<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 script code:

$('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 code:

<?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 = '[email protected]';                 // Наш логин
$mail->Password = 'qwerty34';                           // Наш пароль от ящика
$mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465;                                    // TCP port to connect to
 
$mail->setFrom('[email protected]', 'Школа Немецкого Языка');   // От кого письмо 
$mail->addAddress('[email protected]');     // 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;
}

?>

Answer the question

In order to leave comments, you need to log in

5 answer(s)
A
Alexander Kurbatov, 2019-08-24
@Nub_Ready

Connected jquery at the beginning of the document

<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>

And the script itself at the end of the document:
<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>

The script itself looks like this: 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;
  });
});

The page still reloads with a white screen

T
ThunderCat, 2019-08-24
@ThunderCat

$(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;
  });
})

G
Grigory Vasilkov, 2019-08-24
@gzhegow

Maybe you hang up your script on onSubmit even before the jquery which has async is loaded?

F
FKV, 2019-08-24
@FKV

Connect jQuery before the submit script and wrap it in

$(document).ready(function (){
Твой код
});

M
Michael, 2019-08-24
@MikeDeblin

remove action from form.
Then watch what JS does

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question