<form action="mail-call.php" method="post"> <p>Заказать звонок</p> <input type="text" placeholder="Ваше имя" name="name" required> <input type="text" placeholder="Ваш телефон" name="tel_number" required> <button name="reserve_submit">Заказать звонок</button> </form> 

This is a form code with a button. After clicking and successful field validation, an email is sent using phpmailer .

I want to change the text on the button with the successful sending of the letter. For onlick text will change even if the fields are filled incorrectly.

What event (or something else) can be attached to correctly implement it?

I thought what can be done via button.onsubmit = function() {this.innerHTML = 'Отправлено'} , but apparently this event is for other purposes ...

  • Provide a code to send data (those that are on the JS ) and what the server can respond with on success and an error. - user207618
  • @Other if I understand you correctly, I do not use JS for these purposes. for all sending goes via php: starting with <?php if(isset( $_POST['reserve_submit'] )) { ... the message body is formed ... and ending with '$ mail-> Send ();' - lexxl
  • If so, then the text change dynamically will not work. Either reloading the page and instead of the form a beautiful sign "Sent!", But this is not a trend for a long time, now forms without AJAX are something from the era of Australopithecus (not always, but in general ...). - user207618
  • @Other and can you give an example of an ajax request, in which it will be, to which it will bind to solve my problem? - lexxl

3 answers 3

What event (or something else) can be attached to correctly implement it?

As far as I understand, you, for some reason, need to make this action "inline", in this case, listen to the submit event on the form. But in a good way , you need to make sure that the letter was actually sent and the server answered positively.

  <form action="mail-call.php" method="post" onsubmit="_onSubmit(event)"> <p>Заказать звонок</p> <input type="text" placeholder="Ваше имя" name="name" required> <input type="text" placeholder="Ваш телефон" name="tel_number" required> <input type="submit" name="reserve_submit" value="Заказать звонок"> </form> <script> function _onSubmit(e) { document.forms[0].elements[2].value = 'Отправлено!'; e.preventDefault(); // debug purposes } </script> 

    At the request of the following example of AJAX send:

     // mail-call.php // Получаем данные, обрабатываем, отправляем и пр. $name = trim($_POST['name']); $phone = trim($_POST['tel_number']); $response = [ 'status' => false ]; if($name === '' || $phone === '') $response['error'] = 'Имя и телефон должны быть заполненными'; else if(!preg_match('/^\d\-\d{3}\-\d{3}$/', $phone)) $response['error'] = 'Телефон должен быть вида: 1-234-567'; else{ $response['status'] = true; $response['name'] = $name; $response['phone'] = $phone; } print json_encode($response); // Страница заказа <form action="/mail-call.php" method="post" id='orderForm'> <p>Заказать звонок</p> <input type="text" placeholder="Ваше имя" name="name" required> <input type="text" placeholder="Ваш телефон" name="tel_number" required> <button name="reserve_submit">Заказать звонок</button> </form> <script> function submitHandler(e){ // Ищем кнопку отправки (в ней будем писать ответ) и предотвращаем стандартное действие браузера let submit = this.querySelector('[name="reserve_submit"]'); e.preventDefault(); // Это новый метод запросов, в старых браузерах не работает // Но удобный, отправляет всё в PHP-обработчик fetch(this.action, { method: this.method, body: new FormData(this) }).then(raw => raw.json().then(success => { // Как только получили ответ, смотрим статус if(success.status){ // Отлично, пишем что всё отправилось submit.innerHTML = success.name + ", принято на: " + success.phone; }else{ // Если статус провалил явки, можно написать причину // В моём примере в ответ добавляется причина (error) submit.innerHTML = "Произошла ошибка: " + success.error; } })).catch(error => // Если произошла ошибка в JS, обрабатываем тут submit.innerHTML = "Ошибка отправки" ); } document.addEventListener('DOMContentLoaded', e => { // Навешиваем обработчик отправки на форму document.querySelector('#orderForm').addEventListener('submit', submitHandler); }); </script> 

    Sample Worker, PHP5.6 , Chrome50 , FF42 .

      Solved the problem as follows:

      PHP:
      at the end of the file I entered a variable to receive it as a confirmation from the server that everything went well

       <?php if( $_POST ) { ... ... // формирование тела письма и вызов класса 'class.phpmailer.php' ); ... if ( $mail->send() ) { $result = '1'; } else { $result = '0'; } die( $result ); // завершение работы скрипта и вывод результата в переменную } ?> 

      Js:
      Using jQuery, formed an AJAX request

       var data = $('#modalCallOrder form').serialize(); // собираю и упорядочиваю данные в форме $.ajax({ url: "mail.php", // путь к файлу с кодом для формирования тела письма type: "POST", // указываю метод отправки data: data, // указываю данные для передачи на сервер beforeSend: function() { $('#modal button').text('Отправляется...'); // перед отправкой письма меняю текст кнопки }, success: function(result) { // получаю ответ от сервера if ( result == 1 ) { // если 1, значит письмо отправлено console.log('Письмо отправлено'); $('#modal button').text('Отправлено'); // после отправки письма меняю текст кнопки $('#modal form').find('input').val(''); // очищаю введённые значения } else { console.log('Ошибка отправки'); } }, error: function() { console.log('Ошибка доступа') } }) 

      HTML:
      The form code cleared from the data about the path to the php-file and the method of sending

       <form> <p>Заказать звонок</p> <input type="text" placeholder="Ваше имя" name="name" required> <input type="text" placeholder="Ваш телефон" name="tel_number" required> <button>Заказать звонок</button> </form>