[英]Form is not submited after form submit button click with javascript event listener
我创建了一个表格。 javascript 一切正常,但主要问题是我单击提交按钮后没有提交和发送我的表单。 如果我注释掉event.preventDefault();
比点击提交按钮后,它刷新页面并提交表单。 您知道如何防止页面刷新并在单击提交按钮后提交表单吗?
代码如下。 提前致谢。
HTML
<form action="" method="post" id="formId">
<p class="email">Email<span style="color:red">*</span><br/>
<input type="email" placeholder="Enter your email" name="users_email" size="40" required>
<input type="submit" class="btn" name="send-form" value="ODOBERAŤ NOVINKY">
</p>
<p id="opTag" class="textove"></p>
</form>
JS
var form = document.getElementById("formId");
var opTag = document.getElementById("opTag");
function submitForm(event) {
event.preventDefault();
form.style.display = "none";
opTag.innerHTML = "Thank you. Your form has been sent.";
var expDate = new Date();
expDate.setTime(expDate.getTime() + (24 * 60 * 60 * 1000 * 1000));
$.cookie("hidepopup", "hide", { path: '/', expires: expDate });
}
form.addEventListener('submit', submitForm);
更新:提交表格后,我需要运行这个 php 来订阅 mailchimp API。
PHP 代码如下
function send_mail() {
// if the submit button is clicked, add to subscriber
if ( isset( $_POST['send-form'] ) ) {
$apiKey = 'xxxxxxx';
$users_email = $_POST['users_email']; // the user email we are going to subscribe
$list_id = 'xxxxxxx'; // List / Audience ID
$server = explode( '-', $apiKey );
$url = 'https://' . $server[1] . '.api.mailchimp.com/3.0/lists/' . $list_id . '/members/';
$response = wp_remote_post(
$url,
[
'method' => 'POST',
'data_format' => 'body',
'timeout' => 45,
'headers' => [
'Authorization' => 'apikey ' . $apiKey,
'Content-Type' => 'application/json; charset=utf-8',
],
'body' => json_encode(
[
'email_address' => $users_email,//email
'status' => 'subscribed',
'status_if_new' => 'subscribed',
]
)
]
);
}
}
event.preventDefault();
防止默认行为发生,因此在您的情况下,在表单上使用它会阻止正常过程发生,即发布表单并刷新页面。
由于您正在使用event.preventDefault();
您将需要编写一些额外的 JS 来获取您的表单输入并对其进行处理。
我已经为类似于您的情况编写了一些示例 JS。
var form = document.getElementById("formId"); var opTag = document.getElementById("opTag"); function submitForm(event) { event.preventDefault(); console.log("form submitted"); // logs "form submitted" to the console when submit button is clicked. opTag.innerHTML = "Thank you. Your form has been sent."; // Gives user a message // You want to do something with your form data here // For example grab your input, clear it and do something with it... let inputField = document.querySelector('.email-field'); let inputValue = inputField.value; // get the value inputField.value = ""; // clear the field once submit is clicked console.log(inputValue) // Logs the value entered into email fields after submit is clicked // Send a ajax post request to somewhere // Create and Send the request var fetch_status; fetch('https://jsonplaceholder.typicode.com/users', { method: "POST", // Set the headers headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, // Set the post data body: JSON.stringify({ email: inputValue, }) }).then(function (response) { // Save the response status in a variable to use later. fetch_status = response.status; // Handle success // eg. Convert the response to JSON and return return response.json(); }).then(function (json) { // Check if the response were success if (fetch_status == 201) { // Use the converted JSON console.log(json); } }).catch(function (error){ // Catch errors console.log(error); }); } form.addEventListener('submit', submitForm);
<form action="" method="post" id="formId"> <p class="email">Email<span style="color:red">*</span><br/> <input class="email-field" type="email" placeholder="Enter your email" name="users_email" size="40" required> <input type="submit" class="btn" name="send-form" value="ODOBERAŤ NOVINKY"> </p> <p id="opTag" class="textove"></p> </form>
您的问题应该是由form
标签的action
属性引起的。 如果将其留空,则默认行为是刷新当前页面。 要修复它,您必须将必须处理表单请求的后端页面放在action
属性中。
请注意,使用上述建议的解决方案,您将收到响应 html 页面,该页面将覆盖您的当前页面。如果您想保留当前页面,您必须使用 ajax 并使用 ajax 调用您的服务器页面。这里有一个 php 的示例: 如何使用 AJAX 提交此表单而不使用 jQuery 而使用纯 Javascript
您可以使用fetch
来执行 AJAX 请求。
function submitForm(event) {
event.preventDefault();
// ...
fetch(form.action, {method: form.method, body: new FormData(form)}).then(res => {
// use response here...
// e.g. res.json() returns a Promise resolving to the result of parsing the body as JSON
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.