There is a simple form, which turned out to send, but I do not understand why the page reloads? ajax should send without rebooting. What am I doing wrong? In addition, the url fits all the data from the form, even after a reboot. In general, something goes wrong, but what exactly can not figure out who can, tell me pliz ...

 $(document).ready(function () { $("#form").submit(function() { var form_data = $(this).serialize(); $.ajax({ type: "POST", url: "send.php", data: form_data, success: function() { alert("Ваше сообщение отпрвлено!"); } }) }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form class="contact-form" name="myForm" id="form"> <div class="contact-form__item"> <input class="contact-form__input" type="text" name="Name" placeholder="ФИО"> </div> <div class="contact-form__item"> <input class="contact-form__input" type="tel" name="Phone" id="tel" placeholder="+38 (099) 000-00-00"> </div> <div class="contact-form__item"> <input class="contact-form__input" type="email" name="Email" placeholder="Email"> </div> <div class="contact-form__item"> <select class="contact-form__input" name="Select"> <option>Тестирование сайта</option> <option>Тестирование моб. приложения</option> <option>Тестирование прототипа</option> <option>Тестирование веб-сервиса</option> <option>Другое</option> </select> </div> <div class="contact-form__item"> <textarea class="contact-form__textarea" name="Message"></textarea> <input class="btn-main contact-form__submit" type="submit" value="Бесплатная Консультация"> </div> </form> 

    1 answer 1

    Help you: preventDefault();

     $("#form").submit(function(e) { // e - от слова event, текущее событие e.preventDefault(); $.ajax({ type: "POST", url: "send.php", data: $(this).serialize(e), success: function(r) { // r - от слова response - ответ сервера alert("Ваше сообщение отпрвлено!"); } }) }); 

    Now I’ll explain: You are listening to a submit event. How does it work normally? Reloads the page and roughly sends the data from the form. So you need to intercept the standard browser behavior such as reloading and sending data, and instead do something different, in this case: send AJAX, for this we pass the event e itself to the function, and preventDefault(); it from preventDefault();

    More details here: https://learn.javascript.ru/default-browser-action

    • But in this case, the data in the form remains. Will I need to clear all form fields after submitting? Specially? And why are the parameters passed to the url? Is this ajax feature? - max
    • In the url, nothing should be transmitted when we send it by an Ajax, the form is cleaned by hands like so $('form').trigger('reset'); - ferrari
    • Thanks for explaining this. I also want to clarify, is this a normal practice? For some reason I immediately thought that it was a caste - max
    • @max practice is normal, everything is fine. - ferrari