如何通过AJAX POST向HTTPS的PHP发送表单及Prompt数据至phpMyAdmin
Got it, let's work through this problem together. You're trying to send form data via AJAX POST to an HTTPS endpoint, capture a username with a prompt, and save everything to a phpMyAdmin database—but your earlier XMLHttpRequest attempts failed. Let's fix this step by step:
First, we'll replace that inline onclick with a cleaner event listener, grab the username via prompt, package it with your form data, and send it securely over HTTPS. I'll show you both modern fetch and classic XMLHttpRequest versions (since you mentioned XHR earlier):
Option 1: Using Fetch API (Modern & Recommended)
// Wait for the page to load before attaching events document.addEventListener('DOMContentLoaded', function() { const submitBtn = document.getElementById('start_button'); submitBtn.addEventListener('click', function() { // Get username from prompt const username = prompt('Please enter your username:'); if (!username) { alert('Username is required to proceed!'); return; } // Collect form data const form = document.getElementById('user_form'); const formData = new FormData(form); // Add the prompt username to the form data formData.append('username', username); // Send POST request to your HTTPS endpoint fetch('https://foo.com/Pages/Intro/Intro.php', { method: 'POST', body: formData, credentials: 'same-origin' // Include this if you need to send cookies (e.g., user sessions) }) .then(response => { if (!response.ok) throw new Error(`Request failed: ${response.status}`); return response.text(); // Use response.json() if your PHP returns JSON }) .then(result => { console.log('Success:', result); alert('Your data has been saved successfully!'); }) .catch(error => { console.error('Error:', error); alert('Oops, something went wrong. Check the console for details.'); }); }); });
Option 2: Using XMLHttpRequest (For Legacy Support)
If you need to stick with XHR, here's the corrected version (the HTTPS protocol itself doesn't break XHR—likely a configuration issue before):
document.addEventListener('DOMContentLoaded', function() { const submitBtn = document.getElementById('start_button'); submitBtn.addEventListener('click', function() { const username = prompt('Please enter your username:'); if (!username) { alert('Username is required to proceed!'); return; } const form = document.getElementById('user_form'); const formData = new FormData(form); formData.append('username', username); const xhr = new XMLHttpRequest(); xhr.open('POST', 'https://foo.com/Pages/Intro/Intro.php', true); // Uncomment below if you need to send cross-domain cookies (only if allowed by CORS) // xhr.withCredentials = true; xhr.onload = function() { if (xhr.status >= 200 && xhr.status < 300) { console.log('Success:', xhr.responseText); alert('Your data has been saved successfully!'); } else { console.error('Request failed:', xhr.statusText); alert('Oops, something went wrong.'); } }; xhr.onerror = function() { console.error('Network error occurred'); alert('Could not connect to the server.'); }; xhr.send(formData); }); });
Now update your Intro.php file to handle the POST request, validate input, and insert data into your database. Always use prepared statements to prevent SQL injection:
<?php // Database configuration (update these with your phpMyAdmin details) $servername = "localhost"; // Usually localhost for phpMyAdmin $dbUsername = "your_database_username"; $dbPassword = "your_database_password"; $dbName = "your_database_name"; // Create database connection $conn = new mysqli($servername, $dbUsername, $dbPassword, $dbName); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Retrieve POST data (sanitize and validate!) $username = trim($_POST['username'] ?? ''); // Replace these with your actual form field names $formField1 = trim($_POST['your_form_field_1'] ?? ''); $formField2 = trim($_POST['your_form_field_2'] ?? ''); // Basic validation if (empty($username)) { echo "Error: Username is required."; exit; } // Use prepared statement to insert data (prevents SQL injection) $stmt = $conn->prepare("INSERT INTO your_table_name (username, field1, field2) VALUES (?, ?, ?)"); // Bind parameters: "sss" means 3 string values (adjust for int/double with "i"/"d") $stmt->bind_param("sss", $username, $formField1, $formField2); if ($stmt->execute()) { echo "Data saved successfully!"; } else { echo "Error: " . $stmt->error; } // Cleanup $stmt->close(); $conn->close(); ?>
- Mixed Content Block: If your webpage is served over HTTP but you're trying to send to an HTTPS endpoint, browsers block this. Fix it by serving your page over HTTPS too.
- Cross-Origin Issues: If your page isn't hosted on
https://foo.com, you'll need to add CORS headers to your PHP file to allow the request:header("Access-Control-Allow-Origin: https://your-page-domain.com"); header("Access-Control-Allow-Methods: POST"); header("Access-Control-Allow-Headers: Content-Type"); - Incorrect FormData Handling: Maybe you didn't properly add fields or send the data as
multipart/form-data(usingFormDatahandles this automatically). - Console Debugging: Press F12 to open browser dev tools—check the Network tab to see the request status, and Console for errors. This is the fastest way to spot issues.
内容的提问来源于stack exchange,提问作者Dimitriy Kruglikov

