
function doPost(e) {
let ss = SpreadsheetApp.openById("123123asdasd"); // Change "SpreadsheetAppId" to your actual sheet id
let sheet = ss.getSheetByName("Sheet1"); // Change "Sheet1" to your actual sheet name
let data;
try {
data = JSON.parse(e.postData.contents);
} catch (err) {
data = e.parameter;
}
sheet.appendRow([data.fname, data.email, data.message]);
return ContentService.createTextOutput("Success").setMimeType(ContentService.MimeType.TEXT);
}
Explanation:
function doPost(e)
let ss = SpreadsheetApp.openById("123123asdasd");
var sheet = ss.getSheetByName("Sheet1");
try { data = JSON.parse(e.postData.contents); } catch (err) { data = e.parameter; }
sheet.appendRow([data.fname, data.email, data.message]);
return ContentService.createTextOutput("Success").setMimeType(ContentService.MimeType.TEXT);
4. Deploy the Script as a Web App
5. PHP Code to Submit Form Data to Google Apps Script Web App
Html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Submit Form</title>
</head>
<body>
<form method="post" action="submit.php">
<label for="name">Name:</label>
<input type="text" name="name" required><br>
<label for="email">Email:</label>
<input type="email" name="email" required><br>
<label for="message">Message:</label>
<textarea name="message" required></textarea><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
PHP code:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$url = 'YOUR_WEB_APP_URL'; // Replace with your Google Apps Script Web App URL
$postData = array(
'name' => $_POST['name'],
'email' => $_POST['email'],
'message' => $_POST['message'],
);
$ch = curl_init($url);
$postFields = http_build_query($postData);
curl_setopt($ch, CURLOPT_POST, 1); // Send a POST request
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields); // Attach the POST fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the response as a string
$response = curl_exec($ch);
if ($response === false) {
$error = curl_error($ch);
echo "cURL error: $error";
} else {
echo "Server response: $response";
}
curl_close($ch);
}
?>
The above is the detailed content of How to Integrate Google Sheets with a PHP Website Form: Step-by-Step Guide. For more information, please follow other related articles on the PHP Chinese website!