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

PHP+AJAX登录表单问题:output函数返回JSON而非跳转至受保护页面

Hey there, let's work through this login redirect issue step by step—you're really close, just missing a few key pieces!

The Core Problem

Right now, your PHP is correctly returning JSON on login success/failure, but your client-side JS isn't using that response to trigger a redirect. Plus, there are a couple of critical gaps in your code that are keeping the whole flow from working as intended.


Step 1: Fix the PHP Side

First, let's shore up your backend code to ensure sessions work and you're protected from SQL injection:

<?php
session_start(); // 🔑 Must start the session to save login state
include('functions.php');
// Assume your $db PDO connection is initialized here

if(!empty($_POST)){
    $Return = array('result'=>array(), 'error'=>'');
    $email = $_POST['Email'];
    $password = $_POST['Password'];

    // Keep your existing validation logic
    if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $Return['error'] = "Please enter a valid Email address.";
    } else if($password === '') {
        $Return['error'] = "Please enter Password.";
    }
    if($Return['error']!='') {
        output($Return);
    }

    // 🛡️ Use prepared statements to prevent SQL injection (never concatenate user input!)
    $query = $db->prepare("SELECT Email FROM USERS WHERE Email=? AND Password=?");
    $query->execute([$email, $password]);
    $result = $query->fetch(PDO::FETCH_ASSOC);

    if($query->rowCount() == 1) {
        $_SESSION['UserData'] = $result;
        // Add clear flags for the client to act on
        $Return['result']['success'] = true;
        $Return['result']['redirect_url'] = 'protected_page.php'; // Replace with your actual protected page path
    } else {
        $Return['error'] = 'Invalid Login Credential.';
    }
    output($Return);
}
?>

Step 2: Fix the Client-Side JS

Your AJAX request was missing two huge pieces: passing the form data, and handling the redirect on success. Here's the updated code:

$('#login_form').submit( function(event) {
    // 🚫 Stop the default form submission (prevents page refresh)
    event.preventDefault();

    new Ajax.Request('./submit.php', {
        method:'post',
        // 📤 Send the form data to the server (you forgot this earlier!)
        parameters: $('login_form').serialize(),
        requestHeaders: {Accept: 'application/json'},
        onSuccess: function(transport){
            var json = transport.responseText.evalJSON(true);
            
            if(json.error) {
                // Show error message if login failed
                alert(json.error);
            } else {
                // ✅ Login succeeded—redirect to protected page
                alert("Login successful! Redirecting...");
                window.location.href = json.result.redirect_url;
            }
        },
        onFailure: function() {
            alert("Oops, something went wrong with the request.");
        }
    });

    return false; // Extra safety to block default submission
});

Step 3: Secure Your Protected Page

Don't forget to add session validation to your protected page (e.g., protected_page.php) to ensure only logged-in users can access it:

<?php
session_start();
if(!isset($_SESSION['UserData'])){
    // Redirect unauthenticated users back to login
    header("location: login.php");
    exit;
}
// Your protected content goes here
?>

Key Fixes Recap

  1. Session Initialization: session_start() is required to save and retrieve user login state across pages.
  2. Form Data Passing: $('login_form').serialize() sends the email/password to your backend—without this, your PHP never gets the login credentials!
  3. Client-Side Redirect: Using window.location.href in the onSuccess handler tells the browser to navigate to the protected page once login is confirmed.
  4. SQL Injection Protection: Prepared statements keep your database safe from malicious user input.

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

火山引擎 最新活动