I have created a form. Everything works perfect with javascript but the main problem is that my form is not being submited and sent after I click the submit button. If I comment out the event.preventDefault();
than after submit button is clicked, it refresh the page and submits the form. Do you have any idea how can I prevent the page to be refreshed and submit the form after the submit button is clicked?
Code bellow. Thanks in advance.
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);
UPDATE: After the form is submitted I need to run this php to subscribe to mailchimp API.
PHP code bellow
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',
]
)
]
);
}
}