如何完善基于Promise与jQuery Ajax的OTP验证交互逻辑?
Fixing Your OTP Verification Flow with jQuery AJAX & Promises
Let's walk through fixing your OTP verification flow step by step—your current code has a few small issues that are keeping it from working as intended, plus we'll tighten up the backend logic to make the whole process more reliable.
First, Let's Fix the Frontend JavaScript
Your original code has redundant (and broken) Promise handling, plus a syntax error in the button disable logic. Here's the corrected version:
Updated submit_otp Function
function submit_otp(){ var otp = jQuery('#otp').val(); // jQuery's AJAX already returns a Promise-compatible jqXHR object return jQuery.ajax({ url: '../../../Code_Verification/check_otp.php', type: 'post', data: { otp: otp }, // Using an object for data is cleaner & avoids string concatenation bugs dataType: 'json' // Tell jQuery we expect a JSON response from the server }); }
Updated Promise Callback Logic
submit_otp() .then(function(response) { // Check if the backend confirmed the OTP is valid if (response.success) { FrontendBook.updateConfirmFrame(); // Navigate to the next page } else { // Trigger the error handler if OTP is invalid throw new Error('Invalid OTP'); } }) .fail(function() { jQuery('#otp_error').html('Please enter your valid OTP'); // Fixed the attribute name (it's "disabled", not "disable") $('#button-next-3').attr('disabled', true); $('#button-next-3').css('cursor', 'not-allowed'); });
Key Frontend Fixes Explained
- Removed redundant Promise creation: jQuery's
$.ajaxreturns a jqXHR object that already behaves like a Promise—no need to wrap the success callback in a new (and typo-ridden)Promiseconstructor. - Switched to JSON responses: Using JSON instead of plain strings avoids bugs from accidental whitespace/newlines in the backend's output.
- Fixed button disable syntax: Changed
disabletodisabled(the correct HTML attribute name) so the button actually gets disabled.
Now, Let's Solidify the Backend check_otp.php
Your PHP script needs to reliably validate the OTP against your database, then return a clear JSON response. Here's a robust example:
<?php // Start session if you stored the OTP in the user's session (common practice) session_start(); // Connect to your database (replace with your actual DB credentials) $conn = mysqli_connect('localhost', 'username', 'password', 'your_database'); if (!$conn) { die(json_encode(['success' => false])); } // Sanitize the incoming OTP to prevent SQL injection $input_otp = mysqli_real_escape_string($conn, $_POST['otp'] ?? ''); // Example: Fetch the stored OTP from your database (adjust the query to match your schema) // Assuming you have a table like `user_otps` with `user_id`, `otp`, and `expires_at` columns // Replace $_SESSION['user_id'] with how you track the logged-in user $user_id = $_SESSION['user_id'] ?? ''; $query = "SELECT otp FROM user_otps WHERE user_id = '$user_id' AND otp = '$input_otp' AND expires_at > NOW()"; $result = mysqli_query($conn, $query); $response = ['success' => false]; // Check if the OTP exists and is still valid if (mysqli_num_rows($result) > 0) { $response['success'] = true; // Delete the used OTP to prevent reuse mysqli_query($conn, "DELETE FROM user_otps WHERE user_id = '$user_id' AND otp = '$input_otp'"); } // Return JSON response header('Content-Type: application/json'); echo json_encode($response); mysqli_close($conn); exit; ?>
Backend Improvements Explained
- SQL injection protection: Used
mysqli_real_escape_stringto sanitize the input OTP. - Expiry check: Added
expires_at > NOW()to ensure the OTP hasn't expired (you'll need to add this column to your OTP table and set an expiry when sending the OTP). - OTP cleanup: Deletes the used OTP after successful validation to prevent reuse.
- Consistent JSON response: Always returns a JSON object with a
successboolean, making frontend handling straightforward.
内容的提问来源于stack exchange,提问作者Carmel
相关产品推荐
相关产品推荐

