PHP Mysqli query only runs when I’m not redirecting the page afterwards

Im sitting on a basic login system and for me as a complete beginner I’m happy with it. Right now I try to set the user as online in the database. And this pretty much works. The problem is that when I redirect the user to the profile page the query doesn’t seem to work anymore. As soon as I comment the JavaScript redirection the data changes again. When I take the redirection back inside the data doesn’t change anymore. I’m wondering if I should put sth like a delay between the query and redirection but then how long should I do this to be sure that it worked? I don’t want a loop that runs the whole time and asks if the data changed. The redirection works, so the code runs through. Just the data doesn’t get updated.

require("mysql.php");
            $query = "SELECT * FROM userdata WHERE username = '".$username."' AND password = '".$password."'";
            $result = mysqli_query($mysqli, $query);
            if(mysqli_num_rows($result)>0) { //if > 0 that means that an account has been found
                $_SESSION['username'] = $username;
                $_SESSION['loggedin'] = 1;
                $query = "UPDATE userdata SET loggedin='Online' WHERE username='".$username."'";
                $result = mysqli_query($mysqli, $query);
                if($result) {
                    echo "<script type='text/JavaScript'>
                        var name = '$username';
                        window.location.assign('/profile.php?name='+name);
                    </script>"; //redirect to the profile page after login
                }
                else {
                    echo musqli_error($mysqli);   
                }
            }  

I tried several things to check if the code even runs completely, I replaced the redirection with a simple alert, this made the data to update but of course then I don’t get redirected anymore. But the alert was shown what means that it’s working. The redirection itself works as well. Just the combination of the data update and redirection seems wrong.