我开发了一个与 Mailchimp API 集成的联系表单插件。问题出在 ajax 函数内的 app.js 文件中,其中数据为空(数据未正确传递到此文件)。你能帮我解决这个问题吗?以下是我的插件中的文件:
联系表单.php:
<form id="contactform" method="post" action="<?php echo plugin_dir_url(__FILE__) . 'action.php';?>">
// inputs
</form>
action.php:
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
class ContactFormHandler {
private $apiKey;
private $listID;
public function __construct($apiKey, $listID) {
$this->apiKey = $apiKey;
$this->listID = $listID;
}
public function processForm() {
if (isset($_REQUEST['email'])) {
$result = [];
$sendToMailchimp = isset($_REQUEST['sub_status']) ? true : false;
$fname = $_REQUEST['fname'];
$lname = $_REQUEST['lname'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
$company = $_REQUEST['company'];
$status = $_REQUEST['sub_status'];
$email_valid = filter_var($email, FILTER_VALIDATE_EMAIL);
if ($email_valid) {
$this->sendEmail($fname, $lname, $email, $message, $company, $status, $result);
if ($sendToMailchimp) {
$this->sendToMailchimp($fname, $lname, $email, $company, $result);
}
} else {
$result['notvalid'] =true;
}
wp_send_json_success($result);
}
}
private function sendEmail($fname, $lname, $email, $message, $company, $status, &$result) {
// $email_destination = get_option('email_destination');
// $to = empty($email_destination) ? '[email protected]' : $email_destination;
$to = "[email protected]";
$subject = 'New Message Form Contact Form';
$email_message = "Name: $fname $lname\nEmail: $email\nStatus: $status\nCompany: $company\nMessage: $message";
$headers = "From: " . $fname . $lname . " <" . $email . "> \r\n";
$send_email = mail($to, $subject, $email_message, $headers);
if ($send_email) {
$result['success'] = true;
} else {
$result['notvalid'] = true;
}
wp_send_json_success($result);
}
private function sendToMailchimp($fname, $lname, $email, $company, &$result) {
$memberID = md5(strtolower($email));
$dataCenter = substr($this->apiKey, strpos($this->apiKey, '-') + 1);
$url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $this->listID . '/members/' . $memberID;
$json = json_encode([
'email_address' => $email,
'status' => 'subscribed',
'merge_fields' => [
'FNAME' => $fname,
'LNAME' => $lname,
'COMPANY' => $company,
],
]);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $this->apiKey);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']); // Set Content-Type
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode == 200) {
$result['sendmail'] = true;
} else if ($httpCode == 214) {
$result['notsendmail'] = true;
} else {
$result['else'] = true;
}
curl_close($ch);
// Only include necessary information in the response
wp_send_json_success($result);
exit; // Terminate the script after echoing the JSON response
}
}
// Usage
$apiKey = 'xxx';
$listID = 'xxxx';
$contactFormHandler = new ContactFormHandler($apiKey, $listID);
$contactFormHandler->processForm();
?>
app.js :
jQuery(document).ready(function($) {
$('#contactform').on('submit', function() {
$('.output_message').text('Loading...');
var form = $(this);
$.ajax({
url: form.attr('action'),
method: form.attr('method'),
data: form.serialize(),
success: function(result) {
const $form_result = JSON.parse(result);
if ($form_result.success) {
$('.output_message').text('Message Sent!');
}
if ($form_result.sendmail) {
$('.output_message').append(' Your email has been added to the newsletter.');
}
}
});
return false;
});
});
联系表单-mailchimp.php:
<?php
/*
Plugin Name: Contact Form Plugin
Description: Custom Contact Form with Mailchimp Integration.
Version: 1.0
*/
session_start();
require_once(plugin_dir_path(__FILE__) . 'action.php');
function enqueue_contact_form_scripts() {
// Enqueue jQuery
wp_enqueue_script('jquery', 'https://code.jquery.com/jquery-3.6.4.min.js', array(), null, true);
// Enqueue app.js
wp_enqueue_script('app', plugin_dir_url(__FILE__) . 'app.js', array('jquery'), null, true);
}
add_action('wp_enqueue_scripts', 'enqueue_contact_form_scripts');
function contact_form_shortcode() {
ob_start();
include(plugin_dir_path(__FILE__) . 'contact-form.php');
return ob_get_clean();
}
add_shortcode('contact_form', 'contact_form_shortcode');
更好的解决方案是制作一个FormData并发送它:
let myform = document.getElementById("contactform");
let data = new FormData(myform);
$.ajax({
url: form.attr('action'),
data: data,
method: form.attr('method'),
....
});