Hello! I can’t send emails via AJAX. I click on the send button and nothing happens. The console does not return any errors. I can not understand where anything is like that ..

HTML

<form action="" method="POST" id="form_question"> <div class="form-row"> <div class="form-group col-md-6"> <label for="user_name">Имя</label> <input type="text" class="form-control" name="user_name" placeholder="Имя" id="user_name" required ><span></span> <label for="user_email">Email</label> <input type="email" class="form-control" name="user_email" placeholder="Email" id="user_email" required ><span></span> <label for="name_category">Выберите категорию</label> <select class="custom-select" name="name_category" id="name_category" required > <option selected value="">Выберите категорию...</option> <option value="Программы">Программы</option> <option value="Ошибки">Ошибки</option> <option value="Игры">Игры</option> <option value="Операционная система">Операционная система</option> <option value="BIOS">BIOS</option> <option value="Комплектующие">Комплектующие</option> <option value="Проблемы с железом">Проблемы с железом</option> </select><span></span> </div> <div class="form-group col-md-6"> <label for="tema">Тема</label> <input type="text" class="form-control" name="tema" id="tema" placeholder="Тема вопроса"><span></span> <label for="message">Ваш вопрос</label> <textarea class="form-control" placeholder="Сообщение..." name="message" id="message" rows="4" required ></textarea><span></span> </div> <button type="submit" class="btn btn-primary col-md-10 mb-4 mx-auto" id="submit">Отправить</button><span></span> </div> </form> 

Js

 $(function(){ $("#form_question").submit(function() { var errors = false; $(this).find('span').empty(); $(this).find('input, option, textarea').each(function(){ if ($.trim( $(this).val() ) == '' ) { errors = true; $(this).next().text('Не заполнено поле ' + $(this).prev().text() ); } }); if ( !errors ) { var data = $('#form_question').serialize(); $.ajax({ url: 'mail.php', type: 'POST', data: data, beforeSend: function(){ $('#submit').next().text('Отправляю...'); }, success: function(res){ if(res == 1){ $('#form_question').find('input:not(#submit), textarea, option').val(''); $('#submit').next().empty(); alert('Письмо отправлено'); } else { $('#submit').next().empty(); alert('Ошибка отправки!'); } }, error: function(){ alert('Ошибка!'); } }); } return false; }); }); 

Php

 <?php if ( $_POST){ require 'phpmailer/PHPMailerAutoload.php'; $mail = new PHPMailer; $mail->isSMTP(); $mail->Host = 'smtp.yandex.ru'; $mail->SMTPAuth = true; $mail->Username = 'voprosy.ssaita@yandex.ru'; $mail->Password = 'vopros.v.o09071993#%'; $mail->SMTPSecure = 'ssl'; $mail->Port = '465'; $mail->CharSet = 'utf-8'; $mail->From = 'voprosy.ssaita@yandex.ru'; $mail->addAddress('healpk@yandex.ru', 'Name'); $mail->addCC('healpk@yandex.ru'); $mail->isHTML(true); $mail->Subject = $_POST['name_category']; $mail->Body = "Привет! Меня зовут: {$_POST['user_name']} Моя почта: {$_POST['user_email']} <br> Категория: {$_POST['name_category']} <br> Тема: {$_POST['tema']} <br> Вопрос: " .nl2br($_POST['message']); $mail->AltBody ="Привет! Меня зовут: {$_POST['user_name']} Моя почта: {$_POST['user_email']} \r\n Категория: {$_POST['name_category']} \r\n Тема: {$_POST['tema']} \r\n Вопрос: {$_POST['message']}"; if ($mail->send() ){ $answer = '1'; } else { $answer = '0'; } die ($answer); } ?> 

Please help me understand and find the error))

  • one
    Well, if the client does not give an error, then see the errors on the server - ArchDemon
  • Try it from easy to hard. First check to the exact date there is a value. Then check that the php file comes. And then you can understand where your mistake is - Pavel8289
  • As for me, using phpMailer for the sake of tect sending is not worth it. Normal mail () can be sent. - Pavel8289
  • At a minimum, put console.log at all stages of the submission - in the body of the submit, in success, in error add the argument xhr and its console too. And look in the console, that works out or not. Maybe you will notice a thread) - Kirill Korushkin

1 answer 1

Try to insert my working version, it just shows how to send a message and take it to php and send it back. Errors can be many, for example, the url is not correct. I advise you to just make a simple request and 1 single answer echo 999; and display this answer in js.you send data and data is not quite logical. Look at me the transfer of the name and value of the variable that php takes. And where you accept it, I did not see. The database can and will be easier connected if in the first variant you received the answer 999 try to take any number from the database and send it to js then you will make sure that it functions correctly. I want to add ajax is a very complicated thing, to understand it is desirable to make a simpler data transfer and understand each line, what goes where and why. var id = 812382;

 var k="Иван"; $.ajax ({ // сам метод ajax url: "ch.php",// куда отправлять type: "POST", // тип отправки data: ({num1: id,num3: k}), // отправляем id и имя dataType: "html", beforeSend: funcBefore, success: function(data){// тут принимает ответ от php // тут получаем ответ alert(data);// должно выйти сообщение данные записаны } } }); // вот эти функция нужны чтобы всё правильно работало function funcBefore () { $("#information").text ("Ожидание данных...") } function funcSuccess (data) { } <?php $mysqli = new mysqli ("localhost", "имя бд", "пар", "имя бд"); // подключение к базе данных $mysqli->query ("SET NAMES 'utf8' "); // кодировка // тут мы принимаем данные $w=$_POST['num1']; // id $w1=$_POST['num3']; // имя $mysqli->query ("UPDATE `название таблицы` SET `name` = '$w1' WHERE `название таблицы`.`id` = $w"); // записываем данные echo "данные записаны"; $mysqli->close();// закрытие бд ?>