There is a script to send data from the form to the mailbox via ajax. The script itself works, the data reaches the mail, but there are no notifications about the successful sending of data.

Tell me, please, how to change the code so that after sending the data, the user is informed that the data has been sent?

<script> $(document).ready(function(){ $("#form").submit(function() { var form_data = $(this).serialize(); $.ajax({ type: "POST", url: "send.php", data: form_data, success: function(response) { alert("Данные отправлены"); document.getElementById(form-result).innerHTML = "Запрос отправлен"; }, error: function(response) { document.getElementById(form-result).innerHTML = "Ошибка при отправке формы"; } }) }) }) </script> 
  • And in the developer panel (F12) in monitoring the network, what answer does the server send? And is there anything in the js console? - andreymal
  • one
    And also, as I understand it, instead of document.getElementById(form-result) should be document.getElementById("form-result") - andreymal
  • his dataType is incorrectly specified for the campaign and because of this an error occurs - ikerya
  • In the console, nothing, put quotes (strange, before this line, in principle, was not and still did not work): alert works, but the message in the form # form-result does not appear - Ruslan
  • And why do requests through the form exactly? - Mr. Black

1 answer 1

You submit the form to reload the page. To prevent this from happening, add return false; in the submit handler:

 $("#form").submit(function() { var form_data = $(this).serialize(); $.ajax({ ... }); return false; }); 

Update

There is a "race condition". Two requests are sent to the server - ajax and submit forms. The order of returning responses to requests is arbitrary. If the answer to submit comes first, the page reloads, and there is nothing to handle success from ajax. If the answer to ajax comes first, an alert is shown, while in the meantime a reply to submit appears - after clicking on OK alert, the page reloads and the html changes disappear.

  • And how does the alert work? - andreymal
  • @andreymal - It does not work. - Igor
  • and comments claim it works - andreymal
  • and how to make, that did not reboot? - Ruslan
  • one
    @andreymal Well, it's simple. There is a "race condition". Two requests are sent to the server - ajax and submit forms. The order of returning responses to requests is arbitrary. If the answer to submit comes first, the page reloads, and there is nothing to handle success from ajax. If the answer to ajax comes first, an alert is shown, while in the meantime a reply to submit appears - after clicking on OK alert, the page reloads and the html changes disappear. - Igor