V
V
Vladimir Pogodaev2020-03-16 15:56:38
AJAX
Vladimir Pogodaev, 2020-03-16 15:56:38

How to check the filled fields on ajax when sending data to the mail?

Hello, I'm just learning js and I need you to help me. Basically what I need. When sending data to the mail, everything works and all the data comes in, a text about successful sending is displayed. I need to validate the entered data so that all fields are filled in, if not, then the error text. All code below

$(document).ready(function(){
            $('.zvonokrecall .button').click(function(){
                // собираем данные с формы
                var user_name = $('#user_name').val();
                var user_email = $('#user_email').val();
                var user_tel = $('#user_tel').val();
                // отправляем данные
                $.ajax({
                    url: "zvonokrecall.php", // куда отправляем
                    type: "post", // метод передачи
                    dataType: "json", // тип передачи данных
                    data: { // что отправляем
                        "user_name": user_name,
                        "user_email": user_email,
                        "user_tel": user_tel,
            "cururl":document.location.href,
            "title":document.title
                    },
                    // после получения ответа сервера

          success: function(response){
            if (response == "0") {
              $(".zvonokrecall .answ").html("Завяка на расчет успешно отправлена - ожидайте ответа!");
              $("#user_name").val("");
              $("#user_email").val("");
              $("#user_tel").val("");
              yaCounter45402159.reachGoal("obratzvonok");
            } else {
              $(".zvonokrecall .answ").html("Заполните поля");
              $("#user_name").val("");
              $("#user_email").val("");
              $("#user_tel").val("");
              
            }
          }
                });
            });

<div class="modal fade zvonokrecall" id="zvonokrecall">
            <div class="modal-dialog">
                <div class="modal-content">
                    <button type="button" class="close" data-dismiss="modal">
            <span aria-hidden="true">&times;</span>
                    </button>
                    <div class="modal-body">
                        <div class="modal-title">Консультация строителя</div>
                        <div class="ok">
                            <i class="fas fa-check"></i>
                        </div>
                        <form action="#" method="post">
                            <div class="input-container">
                                <input class="f_1001" type="text" id="user_name" placeholder="Ваше имя">
                                <input class="f_1002" type="tel" id="user_tel" placeholder="Ваш телефон">
                                <input class="f_1003" type="email" id="user_email" placeholder="Ваш e-mail">
                            </div>
                            <div class="button">Заказать консультацию</div>
                        </form>
                    </div>
                    <div class="modal-footer answ">Наш менеджер свяжется с вами в ближайшее время</div>
                </div>
            </div>
        </div>

<?php

$method = $_SERVER['REQUEST_METHOD'];

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

  $project_name = trim($_POST["project_name"]);
  $admin_email  = "[email protected]";
  $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  = "[email protected]";
  $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 );

echo '0';
?>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mikhail, 2020-03-16
@RuComMarket

I didn’t really get into the code, I’ll just say the methods:
1. set required fields in the tags, on the browser side the form will not be sent until all fields with this parameter are filled. The form should be submitted via submit, not a button click.
2. check each field with js .lenght>0, if lenght=0 display the error text after creating an empty tag (block) for the error
3. you can check it on the back side and give an error in the response, in ajax succes check the response to the error or its absence and how to output to an empty block in method 2

V
Valera Karmanov, 2020-03-16
@motokraft

Include the jQuery Validation Plugin file and add to the beginning of the button click

if(!$(".form-validate-jquery").valid()) { return; }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question