You need the correct example Ajax request to submit the form using jQuery and JavaScript, but so that after sending the form data you do not go to the page that is specified in the "action" attribute of the form. Thank you in advance.
3 answers
$(function() { $('form').submit(function(e) { var $form = $(this); $.ajax({ type: $form.attr('method'), url: $form.attr('action'), data: $form.serialize() }).done(function() { console.log('success'); }).fail(function() { console.log('fail'); }); //отмена действия по умолчанию для кнопки submit e.preventDefault(); }); }); |
$('form').submit(function (e) { e.preventDefault(); var data = $('form').serializeArray(); $.ajax({ type: "POST", url: url, data: data, success: success, dataType: dataType});}); Well, by itself, the url should be the address of the page to which the request is sent. Also, instead of preventDefault you can return the value: return false;
|
$( document ).ready(function() { $("#btn").click( function(){ sendAjaxForm('result_form', 'ajax_form', 'action_ajax_form.php'); return false; } ); }); function sendAjaxForm(result_form, ajax_form, url) { jQuery.ajax({ url: url, //url страницы (action_ajax_form.php) type: "POST", //метод отправки dataType: "html", //формат данных data: jQuery("#"+ajax_form).serialize(), // Сеарилизуем объект success: function(response) { //Данные отправлены успешно result = jQuery.parseJSON(response); document.getElementById(result_form).innerHTML = "Имя: "+result.name+"<br>Телефон: "+result.phonenumber; }, error: function(response) { // Данные не отправлены document.getElementById(result_form).innerHTML = "Ошибка. Данные не отправленны."; } }); } Full example with Backend on php: https://ru.dr-b.com/article/kak-otpravit-formu-bez-perezagruzki-stranici/
|