Frontend
Самая лучшая форма отправки с AJAX
Файл index.php:
$(".jq_form").on('submit', function (event) { event.preventDefault(); var t = $(this); var action = t.attr('action'); var data = t.serialize(); var submit = t.find('.form-submit'); $.ajax({ type: "POST", url: action, data: data, success: function (response) { try { var responseObj = JSON.parse(response); if (responseObj['status'] === true) { submit.empty(); submit.append(responseObj['msg']); submit.prop('disabled', true); } else { console.log(response); } } catch (e) { console.log(response); } } }); }); //varaint vanila js: document.addEventListener("DOMContentLoaded", function() { let forms = document.getElementsByClassName('form_class_for_JS'); for (let form of forms) { form.onsubmit = function (event) { event.preventDefault(); let url = this.getAttribute('action'); let submit = this.querySelectorAll('.form_submit'); let formData = new FormData(this); submit[0].innerHTML = ''; submit[0].append('Загрузка...'); submit[0].setAttribute('disabled', 'true'); return fetch(url, { method: 'POST', body: formData //data }) .then(response => response.json()) .then(data => { if (data['status'] === true) { submit[0].innerHTML = ''; submit[0].append(data.msg); submit[0].setAttribute('disabled', 'true'); window.top.location = "/thankyou_page/"; } else { console.log(data);// Prints result from `response.json()` in getRequest } }) .catch(error => console.error(error)) }; } });
Файл ajax.php:
$to = 'mymail@mail.ru'; $subject = 'blabla'; $message = ''; $message .= 'name - '.preg_replace('/[^А-Яа-яA-Za-z]/','',$_POST['name']).PHP_EOL; $message .= 'phone - '. (int)$_POST['phone']; if (mail($to,$subject,$message)){ echo json_encode(['status' =--> true,'msg' => 'Ваша заявка принята'],JSON_UNESCAPED_UNICODE); } else { echo json_encode(['status' => false]); }
Афоризм дня:
Кто громоздит злодейство на злодейство, свой множит страх. (626)
Leave a reply