Junior2018-04-27 17:07:58
Junior, 2018-04-27 17:07:58

Ajax function is executed twice how can I solve this issue?

I had a problem, the script sends a message to the mail twice, the first with the data that I entered, and the second is empty.
[ htmlform.php ]:

<!DOCTYPE html>
<html lang="ru">
  <meta charset="UTF-8">
  <link rel="stylesheet" href="main.css">
  <form class="form" id="form" name="form">
    <input type="text" class="form-field" name="name" placeholder="Введите ваше имя">
    <input type="text" class="form-field" name="phone" placeholder="Введите ваш телефон">
    <button class="form-button"><span class="text-button">Отправить заявку</span></button>
    <div class="overlay js-overlay-thank-you">
      <div class="popup js-thank-you">
        <h2>Спасибо за заявку</h2>
        <div class="close-popup js-close-thank-you"></div>
  <div id="otv">   
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="main.js"></script>
  <script src="jquery.maskedinput.js"></script>


// Отправка заявки 
$(document).ready(function() {
  $('#form').submit(function() { // проверка на пустоту заполненных полей. Атрибут html5 — required не подходит (не поддерживается Safari)
    if (document.form.name.value == '' || document.form.phone.value == '' ) {
      valid = false;
      return valid;
      type: "POST",
      url: "mail.php",
      data: $(this).serialize()
    }).done(function() {
    return false;
// Закрыть попап «спасибо»
$('.js-close-thank-you').click(function() { // по клику на крестик
$(document).mouseup(function (e) { // по клику вне попапа
    var popup = $('.popup');
    if (e.target!=popup[0]&&popup.has(e.target).length === 0){


if($_POST['name']='' || $_POST['phone']=''){
$recepient = "[email protected]";
$siteName = "Тест";
$from = "test";

$name = trim($_POST["name"]);
$phone = trim($_POST["phone"]);
$message = "Имя: $name \nТелефон: $phone";

$pagetitle = "Заявка с сайта \"$siteName\"";
mail($recepient, $pagetitle, $message, "Content-type: text/plain; charset=\"utf-8\"\n From: $from");
echo 'Сообщение отправлено на '.$recepient;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Troodi Larson, 2018-04-27

Of course you load after sending $('#otv').load('mail.php') a script which is empty.

Alibek Musin, 2018-04-28

Well, what is it? That's the condition
if($_POST['name']=='' || $_POST['phone']==''){

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question