79445947

Date: 2025-02-17 16:03:42
Score: 3
Natty:
Report link

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.');
    }
}

js
<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>
Reasons:
  • Blacklisted phrase (0.5): Thank you
  • Long answer (-1):
  • Has code block (-0.5):
  • Me too answer (2.5): facing the same issue
  • Self-answer (0.5):
  • Low reputation (1):
Posted by: Paris Leasetech