Reputation: 1
I am trying to build a custom communication form (with the Newsletter wordpress plugin). The functionality I am trying to achieve is, inform the admin (of the site) with an email, with the content of the form (name, email, message). And save the customer’s mail address (from the form) to a newsletter’s list, that I have create. The functionality that does not work is the “saving mail” part . The thing is, that I have no errors in logs.
Here are my front end logs, with a success message.
/network/response/https://mylaundryroom.gr/wp-admin/admin-ajax.php?action=custom_tnp
{
"success": true,
"data": "Form submitted successfully, and email saved to newsletter!"
}
Here are my back end logs, with a success message, as well.
/wp-content/debug.log
[11-Feb-2025 15:02:44 UTC] Form captured - Name: paris leasetech, Email: [email protected], Message: Lorem ipsum odor amet, consectetuer adipiscing elit. Nibh nisi nulla nam justo quis phasellus himenaeos pellentesque lobortis. Est turpis urna proin, dolor himenaeos elementum eget. Fusce consectetur praesent etiam morbi dapibus velit bibendum augue nec. Ultricies aenean hendrerit donec maximus himenaeos ornare. Facilisi congue tempus vel orci semper non. Potenti urna elementum magna proin tempor efficitur. Semper pulvinar ad volutpat quis quisque dignissim consequat lectus.
[11-Feb-2025 15:02:44 UTC] Email saved to newsletter list.
Here is my front end code:
HTML
<div class="tnp tnp-subscription">
<!--<form method="post" action="https://mylaundryroom.gr/wp-admin/admin-ajax.php?action=tnp&na=s">-->
<form method="post" action="https://mylaundryroom.gr/wp-admin/admin-ajax.php?action=custom_tnp">
<input type="hidden" name="nlang" value="">
<div class="tnp-field tnp-field-firstname">
<input class="tnp-name" type="text" name="nn" id="tnp-1" placeholder="Ονοματεπώνυμο" required>
</div>
<div class="tnp-field tnp-field-email">
<input class="tnp-email" type="email" name="ne" id="tnp-2" placeholder="Email" required>
</div>
<div class="tnp-field tnp-field-tel">
<input class="tnp-tel" type="tel" name="nu" id="tnp-3" placeholder="Τηλέφωνο" required>
</div>
<div class="tnp-field tnp-field-text">
<textarea class="tnp-text" name="nd" id="tnp-4" placeholder="Αφήστε το μήνυμα σας" required></textarea>
</div>
<div class="tnp-field tnp-field-button">
<input class="tnp-submit" type="submit" value="Αποστολή">
</div>
</form>
</div>
CSS
/* Style for form container */
.tnp-subscription {
max-width: 600px;
margin: auto;
padding: 30px;
background-color: #ffffff;
border-radius: 10px;
}
/* Style for all input fields */
.tnp-field input, .tnp-field textarea {
width: 100%;
padding: 30px; /* Bigger padding for larger size */
border: 2px solid #ccc;
border-radius: 10px;
font-size: 18px; /* Larger font */
background-color: #f5f2ed;
margin-bottom: 15px;
color: #333;
box-sizing: border-box;
}
/* Placeholder text style */
.tnp-field input::placeholder,
.tnp-field textarea::placeholder {
color: #888;
font-size: 16px; /* Larger placeholder size */
text-align: left;
}
/* Textarea specific style (for message) */
.tnp-field textarea {
height: 150px; /* Bigger height for text area */
resize: vertical; /* Allow vertical resizing */
overflow-y: auto; /* Scrollbar appears when content overflows */
line-height: 1.5; /* Spacing between lines */
}
/* Button style */
.tnp-submit {
width: 100%;
background-color: #ffffff;
color: #000000;
font-weight: bold;
text-transform: uppercase;
border: 2px solid #000000;
border-radius: 8px;
padding: 15px;
cursor: pointer;
}
/* Button hover effect */
.tnp-submit:hover {
background-color: #f0f0f0;
}
/* Responsive Design for Tablets */
@media (min-width: 768px) {
.tnp-subscription {
max-width: 800px; /* Increase size on tablets */
padding: 50px;
}
.tnp-field input,
.tnp-field textarea {
font-size: 20px;
padding: 25px; /* Increase padding for larger inputs */
}
.tnp-submit {
font-size: 20px;
padding: 18px;
}
}
/* Responsive Design for Mobile */
@media (max-width: 768px) {
.tnp-subscription {
max-width: 100%;
padding: 15px;
}
.tnp-field input,
.tnp-field textarea {
font-size: 16px;
padding: 15px;
}
.tnp-submit {
font-size: 16px;
padding: 15px;
}
}
JS
<script>
document.addEventListener('DOMContentLoaded', function() {
const form = document.querySelector('.tnp-subscription form');
form.addEventListener('submit', async function(event) {
event.preventDefault(); // Prevent form from submitting the traditional way
const formData = new FormData(form);
// Make an AJAX request to submit the form
try {
let response = await fetch(form.action, {
method: 'POST',
body: formData
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
let result = await response.json();
if (result.success) {
alert('Form submitted successfully!');
form.reset(); // Clear form fields after successful submission
} else {
alert('There was an error submitting the form: ' + result.data);
}
} catch (error) {
console.error('Error:', error);
alert('There was an error submitting the form: ' + error.message);
}
});
});
</script>
And here, is my back end code:
PHP
add_action('wp_ajax_custom_tnp', 'send_form_notification');
add_action('wp_ajax_nopriv_custom_tnp', 'send_form_notification'); // For non-logged-in users
function send_form_notification() {
if (isset($_POST['nn']) && isset($_POST['ne']) && isset($_POST['nd'])) {
$name = sanitize_text_field($_POST['nn']);
$email = sanitize_email($_POST['ne']);
$message = sanitize_textarea_field($_POST['nd']);
// Log form data to debug.log for testing
error_log("Form captured - Name: $name, Email: $email, Message: $message");
// Email recipient and subject
$to = get_option('admin_email');
$subject = 'New Subscription Notification';
// Email message content
$body = "Name: $name\nEmail: $email\nMessage: $message";
// Send email notification
wp_mail($to, $subject, $body);
// Now send the data to the Newsletter plugin for saving the email to the list
// Let's use your new idea for the correct URL
$newsletter_url = 'https://mylaundryroom.gr/wp-admin/admin-ajax.php?action=tnp&na=s';
$response = wp_remote_post($newsletter_url, [
'method' => 'POST',
'body' => [
'ne' => $email, // Email field
'nn' => $name, // Name field
'nd' => $message // Message (if required by the newsletter plugin)
]
]);
// Check if the Newsletter plugin request was successful
if (is_wp_error($response)) {
error_log('Failed to save email to newsletter list.');
wp_send_json_error('Failed to save email to newsletter.');
} else {
error_log('Email saved to newsletter list.');
wp_send_json_success('Form submitted successfully, and email saved to newsletter!');
}
} else {
error_log("Form data is missing or not captured properly.");
wp_send_json_error('Form data is missing.');
}
}
If i do
<form method="post" action="https://mylaundryroom.gr/wp-admin/admin-ajax.php?action=tnp&na=s">
mails saved successfully.. but i don't have the rest functionality i want.. That's why i use
<form method="post" action="https://mylaundryroom.gr/wp-admin/admin-ajax.php?action=custom_tnp">
Also, i use divi's code module for front end code, and code snippet plugin for back end code.
[Edit]
I want to handle the form via AJAX with my custom endpoint, and in the backend, call the Newsletter plugin’s saving functionality programmatically. This will give me both custom notifications and the ability to save emails to the newsletter list without using the Newsletter plugin’s default form submission.
So, i am seeking Newsletter Subscription method (like tnp::subscribe() or tnp()->subscribe()
, or Newsletter::instance()->subscribe()
, etc) witch preforms the subscription, and where is located (something like class-newsletter.php
)
Upvotes: 0
Views: 29
Reputation: 1
I have found a solution!
Thank you all!
Here is my code for any other user, facing the same issue ..
php
add_action('wp_ajax_custom_tnp', 'send_form_notification');
add_action('wp_ajax_nopriv_custom_tnp', 'send_form_notification'); // For non-logged-in users
function send_form_notification() {
if (isset($_POST['nn']) && isset($_POST['ne'])) {
// Sanitize and capture form inputs
$name = sanitize_text_field($_POST['nn']);
$email = sanitize_email($_POST['ne']);
$message = sanitize_textarea_field($_POST['nd']); // Optional
// Log form data to debug.log for testing
error_log("Form captured - Name: $name, Email: $email");
// Email recipient and subject
$to = get_option('admin_email');
$subject = 'New Subscription Notification';
$body = "Name: $name\nEmail: $email\nMessage: $message";
// Send email notification to admin
$headers = array('Content-Type: text/plain; charset=UTF-8');
$mail_result = wp_mail($to, $subject, $body, $headers);
if ($mail_result) {
error_log('Mail sent to admin successfully.');
} else {
error_log('Failed to send mail to admin.');
}
// Check if the Newsletter plugin class exists
if (class_exists('Newsletter')) {
$newsletter = Newsletter::instance();
// Prepare subscriber data
$nl_user = [];
$nl_user['email'] = $email;
$nl_user['name'] = $newsletter->normalize_name($name); // Normalize the name
$nl_user['status'] = 'C'; // Confirmed subscription
$nl_user['surname'] = ''; // Add surname field to avoid missing key issues
$nl_user['sex'] = 'n'; // Add a default value for sex
$nl_user['language'] = ''; // Optional, add a fallback for language
// Add user to forced lists
$lists = $newsletter->get_lists();
// Log all available lists to check "corp_customers" list ID
error_log('Available lists: ' . print_r($lists, true));
$corp_customers_list_id = null;
foreach ($lists as $list) {
if ($list->name === 'corp_customers') { // Check for your specific list
$corp_customers_list_id = $list->id;
$nl_user['list_' . $list->id] = 1; // Add to corp_customers
}
if ($list->forced) {
$nl_user['list_' . $list->id] = 1; // Add to any forced lists
}
}
// Log the "corp_customers" list ID
if ($corp_customers_list_id) {
error_log('corp_customers list ID: ' . $corp_customers_list_id);
} else {
error_log('corp_customers list not found.');
}
// Save user to Newsletter plugin
$result = $newsletter->save_user($nl_user);
// Check the result and handle accordingly
if (is_wp_error($result)) {
error_log('Newsletter plugin error: ' . print_r($result, true));
wp_send_json_error('Failed to save email to newsletter list.');
} elseif (is_object($result) && isset($result->id)) {
error_log('Email successfully saved to newsletter list.');
wp_send_json_success('Form submitted successfully, email saved to newsletter, and notification sent!');
} else {
// Log the complete response from the Newsletter plugin to identify the issue
error_log('Unknown response from Newsletter plugin: ' . print_r($result, true));
wp_send_json_error('Failed to save email to newsletter list. Unknown error.');
}
} else {
error_log('Newsletter plugin class not available.');
wp_send_json_error('Newsletter plugin is not active.');
}
} else {
error_log("Form data is missing or not captured properly.");
wp_send_json_error('Form data is missing.');
}
}
<script>
document.addEventListener('DOMContentLoaded', function() {
const form = document.querySelector('.tnp-subscription form');
form.addEventListener('submit', async function(event) {
event.preventDefault(); // Prevent default form submission
const formData = new FormData(form);
try {
// Send the form data using Fetch API
let response = await fetch(form.action, {
method: 'POST',
body: formData
});
let result = await response.json();
if (result.success) {
alert('Form submitted successfully!');
form.reset(); // Clear form fields after successful submission
} else {
console.error('Error: ' + result.data);
alert('Error: ' + result.data);
}
} catch (error) {
console.error('Error:', error);
alert('There was an error submitting the form: ' + error.message);
}
});
});
</script>
html
<div class="tnp tnp-subscription">
<form method="post" action="https://mylaundryroom.gr/wp-admin/admin-ajax.php?action=custom_tnp">
<input type="hidden" name="nlang" value="">
<div class="tnp-field tnp-field-firstname">
<input class="tnp-name" type="text" name="nn" id="tnp-1" placeholder="Ονοματεπώνυμο" required>
</div>
<div class="tnp-field tnp-field-email">
<input class="tnp-email" type="email" name="ne" id="tnp-2" placeholder="Email" required>
</div>
<div class="tnp-field tnp-field-text">
<textarea class="tnp-text" name="nd" id="tnp-4" placeholder="Αφήστε το μήνυμα σας" required></textarea>
</div>
<div class="tnp-field tnp-field-button">
<input class="tnp-submit" type="submit" value="Αποστολή">
</div>
</form>
</div>
Upvotes: 0