You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

使用Fetch API提交表单数据发邮件为空问题求助

Fixing Your Empty Email Issue with Fetch API & PHP

Hey there, let's break down the issues causing your empty email—this is a super common pitfall with Fetch API, so let's walk through the fixes step by step:

1. Fix the Critical Typo in Your JavaScript

First off, your code snippet cuts off at document.querySelecto...—that's a missing r! You meant document.querySelector('#email'), right? That typo would make your email variable undefined, so that data never gets sent in the first place.

2. Send Data in a Format PHP Can Parse

Fetch doesn't automatically encode data like native form submissions do. If you're just passing a plain object to the body parameter, PHP won't pick it up with $_POST by default. Here are two reliable ways to fix this:

Option A: Use FormData (Simplest for Forms)

FormData handles all encoding automatically, and you don't even need to set custom headers—your browser will take care of it:

(function() {
  const submitBtn = document.querySelector('#submit');
  submitBtn.addEventListener('click', postData);

  function postData(e) {
    e.preventDefault();
    
    // Correct the typo and grab field values
    const first_name = document.querySelector('#name').value;
    const email = document.querySelector('#email').value;
    const message = document.querySelector('#message').value; // Add any other fields you need

    // Build FormData object
    const formData = new FormData();
    formData.append('first_name', first_name);
    formData.append('email', email);
    formData.append('message', message);

    // Send with Fetch
    fetch('your-mail-script.php', {
      method: 'POST',
      body: formData
    })
    .then(response => {
      if (!response.ok) throw new Error('Network response was not ok');
      return response.text();
    })
    .then(data => {
      console.log('Success:', data);
      // Add success UI here (e.g., show a thank you message)
    })
    .catch(error => console.error('Error:', error));
  }
})();

Option B: Use URLSearchParams (For URL-Encoded Data)

If you prefer not to use FormData, you can encode the data manually:

// Inside your postData function
const formData = new URLSearchParams();
formData.append('first_name', first_name);
formData.append('email', email);
formData.append('message', message);

fetch('your-mail-script.php', {
  method: 'POST',
  body: formData,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})
// ... rest of the fetch logic

3. Make Sure Your PHP is Receiving Data Correctly

If you were trying to parse JSON before, that's why $_POST was empty. With the above methods, you can use the standard $_POST superglobal to grab the data safely:

<?php
// Safely retrieve form data (prevents undefined index errors)
$first_name = $_POST['first_name'] ?? '';
$email = $_POST['email'] ?? '';
$message = $_POST['message'] ?? '';

// Validate required fields aren't empty
if (empty($first_name) || empty($email) || empty($message)) {
  echo 'Please fill in all required fields';
  exit;
}

// Send email (basic example)
$to = 'your-target-email@example.com';
$subject = 'New Contact Form Submission';
$body = "Name: $first_name\nEmail: $email\n\nMessage:\n$message";
$headers = "From: $email\r\nReply-To: $email\r\n";

if (mail($to, $subject, $body, $headers)) {
  echo 'Email sent successfully!';
} else {
  echo 'Failed to send email—check your server mail settings';
}
?>

Quick Debugging Tips

  • Open your browser's DevTools → Network tab, and check the Form Data section of your POST request to confirm data is actually being sent.
  • Verify your form fields have matching IDs (e.g., <input id="name"> matches document.querySelector('#name')).
  • Check your PHP error logs if you're still stuck—they might reveal server-side issues with the mail() function or file permissions.

内容的提问来源于stack exchange,提问作者londongrammar

火山引擎 最新活动