[英]Submit a HTML form without redirection and showing a success message
我決定從 WordPress 網站切換到使用 HTML、CSS 和 JS 自制的網站,旨在提高性能。 到目前為止,依靠教程,我已經設法處理了幾乎所有問題,但我無法讓聯系表單像在 WP 中那樣工作。 到目前為止,它將我重定向到另一個顯示成功消息的頁面,這很丑陋。
基本上,我希望提交按鈕做 3 件事: 1. 不要將我重定向到另一個頁面。 2. 重置表格。 3. 顯示成功消息。
在這里閱讀了許多類似的問題,但由於我對 AJAX 完全不熟悉,因此最終決定發布此問題。 這是我的代碼:
索引.html:
<div>
<form method="post" action="form.php" name="myForm">
<input name="name" placeholder="Nombre" required>
<input name="email" type="email" placeholder="Correo Electrónico" required>
<textarea rows="10" name="message" placeholder="Mensaje" required></textarea>
<input id="submit" name="submit" type="submit" value="Enviar Mensaje" class="boton-rojo">
</form>
</div>
並在 form.php 中:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent="De: $name \n Mensaje: $message";
$recipient = "contacto@mydomainname.cl";
$subject = "Mensaje desde el sitio web";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Tu consulta fue recibida";
?>
任何幫助將非常感激。
謝謝。
將 ID 放入您的表單
<form id='myForm'>
....
</form>
使用 jQuery(為了簡單的代碼)
....
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
</body>
使用 $.ajax
$('#myForm').submit(function(e) {
e.preventDefault(); // prevent from submitting form directly
$.ajax({
url: 'form.php',
method: 'post',
data: $("#myForm").serializeArray() // convert all form data to array (key:value)
})
.done(function(response){
alert(response); // show the response
$("#myForm").reset(); // reset the form
})
.fail(function(error){
alert(error); // show the error.
});
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.