Hello everyone, I did not find a normal answer to my question, so I ask it here: HTML + ajax

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Отправка</title> </head> <body> <form id="form" method="POST"> <input type="text" name="name" required="required"/> <input type="text" name="phone" required="required"/> <input type="submit" value="Заказать звонок"/> </form> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#form").submit(function() { //устанавливаем событие отправки для формы с id=form var form_data = $(this).serialize(); //собераем все данные из формы $.ajax({ type: 'POST', //Метод отправки url: 'send.php', //путь до php фаила отправителя data: form_data, success: function(data){ // сoбытиe пoслe удaчнoгo oбрaщeния к сeрвeру и пoлучeния oтвeтa alert('все ок'); // пoкaжeм eё тeкст } }); }); }); </script> </body> </html> 

Now php

 <? if((isset($_POST['name'])&&$_POST['name']!="")&&(isset($_POST['phone'])&&$_POST['phone']!="")){ //Проверка отправилось ли наше поля name и не пустые ли они $to = 'vayka2@yandex.ru'; //Почта получателя, через запятую можно указать сколько угодно адресов $subject = 'Обратный звонок'; //Загаловок сообщения $message = ' <html> <head> <title>'.$subject.'</title> </head> <body> <p>Имя: '.$_POST['name'].'</p> <p>Телефон: '.$_POST['phone'].'</p> </body> </html>'; //Текст нащего сообщения можно использовать HTML теги $headers = "Content-type: text/html; charset=utf-8 \r\n"; //Кодировка письма $headers .= "From: Отправитель <from@example.com>\r\n"; //Наименование и почта отправителя mail($to, $subject, $message, $headers); //Отправка письма с помощью функции mail } ?> 

In short, save the guys for 2 days already I have been fighting him, and he is not working! It is Ajax itself that does not work, because if you write action, php processes and sends the letter, but ajax itself does nothing. What's wrong ? Still correctly written.

UPD: In the debugger, I put a break point, on ajax, the script starts to be executed in the form_data variable, my data is written, then the jquery page goes further and everything is updated. In the console here: TypeError: form.find is not a function

  • What does it mean does not work? Does the console write errors? Do not send ajax request silently? Sent, but not there? Sent, but the server responds with an error? Open the developer tools, see what happens and tell in the text of the question - andreymal
  • Return false or event.preventDefault to cancel the default behavior. - u_mulder

1 answer 1

This line

  $("#form").submit(function() { 

Replace with this

 $("#form").submit(function(e) { e.preventDefault() 

preventDefault () - Cancels an event if it is canceled, without stopping further propagation of this event. A source

Or use

 <button type"button">Сохранить</button> 

With event

 $('#form button').on('click', function () { // Your code }); 
  • Ohhh my God, I fakalsya with this for 2 days. I thought I would shoot myself, thank you, it helped! - lorde