So I have a small user registration form that asks for a username and password built with React. I then send these fields to an insert.php file to add a user to a mySQL database. In the insert.php file I look for any repeat usernames and want to be able to return a message back to my react page. The insertion of users works but cannot return back to initial page from php file if duplicate username is found.
submitting form data to php file:
onSubmit(e){
e.preventDefault();
if (this.state.password === this.state.passwordConform) {
const obj ={
username:this.state.username,
password:this.state.password,
passwordConform:this.state.passwordConform,
};
axios.post('http://localhost/reactProject/insert.php',obj)
.then(res=> console.log(res.data))
.catch(error => {
console.log(error.response)
});
insert.php:
<?php
require 'connect.php';
header("Access-Control-Allow-Origin: http://localhost:3000");
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header("Access-Control-Allow-Headers: Content-Type, Authorization");
function isAvailable($username, $db) { //seeing if there is duplicate username
$sql = "SELECT username FROM users WHERE username='$username'" ;
$result = mysqli_query($db,$sql) ;
if( mysqli_num_rows( $result ) > 0 )
{
return false;
}
return true;
}
$postdata = file_get_contents("php://input");
if(isset($postdata) && !empty($postdata)){
$request = json_decode($postdata);
$username = $request->username;
$password = $request->password;
if($username && $password && isAvailable($username, $db)) {
$sql = "INSERT INTO users (username,password) VALUES ('$username','$password')";
if(mysqli_query($db,$sql)){
http_response_code(201);
}
else{
http_response_code(422);
}
}
else { //error in an input field, just trying to return to a page on my site from php
header('Location: ../login');
exit();
}
}
?>
the php file is within Applications/XAMPP/htdocs/reactProject
the actual react code is in User/React/project_name
I have tried things like header('Location: http://3000/login') which is the exact url of the page i'm wanting to go to. If I type that location directly in my browser it successfully reaches that page. but it will not work from the php file