0

at the end of my code, I use the header function in php to redirect to a different file. i use this elsewhere in my project and it seems to work. but it doesn't work here.

<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    // Read the raw POST data
    $postData = file_get_contents('php://input');

    // Convert the raw POST data to a PHP array
    $formData = json_decode($postData, true);


    $db = new PDO('sqlite:../database.db');

    $hashedPassword = password_hash($formData['password'], PASSWORD_DEFAULT);

    $uniqueId = uniqid();

    $createdAt = date('Y-m-d H:i:s');

    $query = "INSERT INTO users (id, username, email, password, created_at) 
              VALUES (:id, :username, :email, :password, :created_at)";
    $statement = $db->prepare($query);

    // Bind parameters and execute the query
    $statement->bindParam(':id', $uniqueId);
    $statement->bindParam(':username', $formData['username']);
    $statement->bindParam(':email', $formData['email']);
    $statement->bindParam(':password', $hashedPassword);
    $statement->bindParam(':created_at', $createdAt);

    $statement->execute();

    // Set session variables to log in the user
    session_start();
    $_SESSION['user_id'] = $uniqueId;
    $_SESSION['username'] = $formData['username'];

    // Redirect the user to index.php after successful account creation
    header('Location: ../html/index.php');
    exit();
}
?>

and this is my javascript where i fetch the php

    document.getElementById('signup-button-middle').addEventListener('click', handleSignUp);

function handleSignUp() {
    // Get the data from the textareas
    const username = document.getElementById('username').value;
    const email = document.getElementById('email').value;
    const password = document.getElementById('password').value;



    // Create an object with the data to be sent to the PHP file
    const formData = {
        username: username,
        email: email,
        password: password
    };

    // Make a POST request using fetch to send the data to the PHP file in the "PHP" folder
    fetch('../PHP/signup_handler.php', { // Modify the URL to include the "PHP" folder
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(formData)
    })
    .then(response => response.json())
    .then(data => {
        // Handle the response from the PHP file (if needed)
        console.log(data);
        // You can perform additional actions based on the response from the PHP file here.
    })
    .catch(error => {
        // Handle errors, if any
        console.error('Error:', error);
    });
}

when I use JavaScript fetch to execute this code, instead of redirecting to a different page, the html I'm trying to display in the browser shows up in the network tab after I inspect the page

Jake
  • 19
  • 2
  • 1
    *“when I use JavaScript fetch to execute this code”* Please share the code. It looks like the JS is not following the redirection, I think that the expected behaviour, the JS is not a browser. – A.L Jul 31 '23 at 18:55
  • Is this page a being served from an AJAX request? – user3783243 Jul 31 '23 at 19:28

1 Answers1

-1

you can use the window.location.replace("../html/index.php"); in javascript to redirect the user to another page after receiving the PHP response:

php code

<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    // Read the raw POST data
    $postData = file_get_contents('php://input');

    // Convert the raw POST data to a PHP array
    $formData = json_decode($postData, true);


    $db = new PDO('sqlite:../database.db');

    $hashedPassword = password_hash($formData['password'], PASSWORD_DEFAULT);

    $uniqueId = uniqid();

    $createdAt = date('Y-m-d H:i:s');

    $query = "INSERT INTO users (id, username, email, password, created_at) 
              VALUES (:id, :username, :email, :password, :created_at)";
    $statement = $db->prepare($query);

    // Bind parameters and execute the query
    $statement->bindParam(':id', $uniqueId);
    $statement->bindParam(':username', $formData['username']);
    $statement->bindParam(':email', $formData['email']);
    $statement->bindParam(':password', $hashedPassword);
    $statement->bindParam(':created_at', $createdAt);

    $statement->execute();

    // Set session variables to log in the user
    session_start();
    $_SESSION['user_id'] = $uniqueId;
    $_SESSION['username'] = $formData['username'];

}
?>

javascript code

document.getElementById('signup-button-middle').addEventListener('click', handleSignUp);

function handleSignUp() {
    // Get the data from the textareas
    const username = document.getElementById('username').value;
    const email = document.getElementById('email').value;
    const password = document.getElementById('password').value

    // Create an object with the data to be sent to the PHP file
    const formData = {
        username: username,
        email: email,
        password: password
    };

    // Make a POST request using fetch to send the data to the PHP file in the "PHP" folder
    fetch('../PHP/signup_handler.php', { // Modify the URL to include the "PHP" folder
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(formData)
    })
    .then(response => response.json())
    .then(data => {
        // Handle the response from the PHP file (if needed)
        console.log(data);
        window.location.replace("../html/index.php"); //change path if not correct
       // You can perform additional actions based on the response from the PHP file here.
    })
    .catch(error => {
        // Handle errors, if any
        console.error('Error:', error);
    });
} 
  • you're right, and I thought of this as well. however, im more looking for a n explanation as to what I'm doing wrong as opposed to an alternative to fix it – Jake Jul 31 '23 at 21:29
  • Can you get the `Location` header from the response and pass it to `window.location.replace` instead of hardcoding the path in the JS? So that the OP can use the same PHP as in the question. – A.L Jul 31 '23 at 22:00