如何用AJAX与PHP实现Facebook登录并写入MySQL数据库
Got it, let's merge your Facebook login functionality with the AJAX-powered form submission step by step. Here's a complete solution that lets users log in with Facebook, submit reviews without page reloads, and ties everything to your MySQL database:
1. Integrated Main Page (index.php)
This page handles Facebook authentication, displays the user's profile info (if logged in), and includes the AJAX-enabled form. We'll auto-fill the first/last name fields for logged-in Facebook users and add a hidden field to link reviews to their Facebook ID.
<?php // Include FB config and User class require_once 'fbConfig.php'; require_once 'User.class.php'; $fbUser = null; $logoutURL = ''; $oauthUid = ''; if(isset($accessToken)){ if(isset($_SESSION['facebook_access_token'])){ $fb->setDefaultAccessToken($_SESSION['facebook_access_token']); }else{ $_SESSION['facebook_access_token'] = (string) $accessToken; $oAuth2Client = $fb->getOAuth2Client(); $longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']); $_SESSION['facebook_access_token'] = (string) $longLivedAccessToken; $fb->setDefaultAccessToken($_SESSION['facebook_access_token']); } if(isset($_GET['code'])){ header('Location: ./'); exit; } try { $profileRequest = $fb->get('/me?fields=name,first_name,last_name,email,picture'); $fbUserProfile = $profileRequest->getGraphNode()->asArray(); $fbUser = $fbUserProfile; $oauthUid = $fbUserProfile['id']; // Sync Facebook user data to your database $user = new User(); $fbUserData = array( 'oauth_provider'=> 'facebook', 'oauth_uid' => $fbUserProfile['id'], 'first_name' => $fbUserProfile['first_name'], 'last_name' => $fbUserProfile['last_name'], 'email' => $fbUserProfile['email'], 'picture' => $fbUserProfile['picture']['url'], ); $userData = $user->checkUser($fbUserData); $_SESSION['userData'] = $userData; $logoutURL = $helper->getLogoutUrl($accessToken, 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'logout.php'); } catch(FacebookResponseException $e) { echo 'Graph returned an error: ' . $e->getMessage(); session_destroy(); header("Location: ./"); exit; } catch(FacebookSDKException $e) { echo 'Facebook SDK returned an error: ' . $e->getMessage(); exit; } } else { // Generate Facebook login URL $loginURL = $helper->getLoginUrl($redirectURL, $fbPermissions); } ?> <!doctype html> <html> <head> <meta charset="UTF-8"> <title>Facebook Login + AJAX Review Submission</title> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> <style> .response-box { margin-top: 20px; padding: 10px; border-radius: 4px; } .success { background: #d4edda; color: #155724; } .error { background: #f8d7da; color: #721c24; } .profile-section { margin-bottom: 20px; padding: 10px; border-bottom: 1px solid #eee; } </style> </head> <body> <div class="profile-section"> <?php if($fbUser): ?> <h3>Welcome, <?php echo $fbUser['first_name']; ?>!</h3> <img src="<?php echo $fbUser['picture']['url']; ?>" alt="Profile Pic" width="50" height="50"> <p><a href="<?php echo $logoutURL; ?>">Logout from Facebook</a></p> <?php else: ?> <a href="<?php echo $loginURL; ?>">Login with Facebook</a> <?php endif; ?> </div> <form id="reviewForm"> <input type="hidden" name="oauth_uid" value="<?php echo $oauthUid; ?>"> <p>First Name: <input name="namefirst" type="text" id="namefirst" maxlength="35" value="<?php echo $fbUser ? $fbUser['first_name'] : ''; ?>"></p> <p>Last Name: <input name="namelast" type="text" id="namelast" maxlength="50" value="<?php echo $fbUser ? $fbUser['last_name'] : ''; ?>"></p> <p> <label for="text">Review:</label> <textarea name="text" maxlength="65535" id="text" rows="5"></textarea> </p> <p><input type="submit" value="Submit Review"></p> </form> <div id="responseContainer"></div> <script> $(document).ready(function() { $('#reviewForm').submit(function(e) { e.preventDefault(); // Stop page reload on submit // Collect all form data const formData = $(this).serialize(); // Send AJAX request to script.php $.ajax({ url: 'script.php', type: 'POST', data: formData, success: function(response) { // Show success message and reset form $('#responseContainer').html('<div class="response-box success">' + response + '</div>'); $('#reviewForm')[0].reset(); // Re-fill first/last name if user is logged in <?php if($fbUser): ?> $('#namefirst').val('<?php echo $fbUser['first_name']; ?>'); $('#namelast').val('<?php echo $fbUser['last_name']; ?>'); <?php endif; ?> }, error: function(xhr) { // Show error message $('#responseContainer').html('<div class="response-box error">Error: ' + xhr.responseText + '</div>'); } }); }); }); </script> </body> </html>
2. Updated script.php (AJAX Handler)
This script will only accept AJAX requests, sanitize input, and insert the review into your MySQL database. We've switched to prepared statements for better security against SQL injection.
<?php // Block non-AJAX requests if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') { die("Invalid request"); } $servername = "localhost"; $username = "name"; $password = "password"; $dbname = "db"; // Create database connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Sanitize input data $firstname = filter_var(mysqli_real_escape_string($conn, $_POST["namefirst"] ?? ''), FILTER_SANITIZE_STRING); $lastname = filter_var(mysqli_real_escape_string($conn, $_POST["namelast"] ?? ''), FILTER_SANITIZE_STRING); $text = filter_var(mysqli_real_escape_string($conn, $_POST["text"] ?? ''), FILTER_SANITIZE_STRING); $oauthUid = filter_var(mysqli_real_escape_string($conn, $_POST["oauth_uid"] ?? ''), FILTER_SANITIZE_STRING); // Use prepared statement to prevent SQL injection $stmt = $conn->prepare("INSERT INTO tabel (firstname, lastname, text, oauth_uid) VALUES(?, ?, ?, ?)"); $stmt->bind_param("ssss", $firstname, $lastname, $text, $oauthUid); if ($stmt->execute()) { echo "Review submitted successfully!"; } else { echo "Error: " . $stmt->error; } // Clean up connections $stmt->close(); $conn->close(); ?>
Key Integration Details
- Facebook Sync: When users log in with Facebook, their profile data is synced to your database via the
User.class.phplogic, and the form auto-fills their first/last name. - AJAX Submission: The form uses jQuery to send data without reloading the page. The response (success/error) is displayed in a dedicated container.
- Security: We added checks to block non-AJAX requests to
script.php, and used prepared statements to eliminate SQL injection risks. - User Experience: After submission, the form resets (but keeps the user's name if logged in) and clear feedback is shown.
Important Notes
- Database Update: Add an
oauth_uidcolumn (varchar(255)) to yourtabeltable if you want to link reviews to Facebook users. - Facebook Setup: Ensure your
fbConfig.phphas the correct app ID, app secret, and redirect URL. - Client-Side Validation: For better UX, add JavaScript validation to the form (e.g., check that required fields aren't empty) before sending the AJAX request.
内容的提问来源于stack exchange,提问作者user4183285

