dfarrelly dfarrelly - 4 months ago 14
PHP Question

Call Javascript function and execute PHP at the same time?

So I have a form

<form id="login_form" method="post" action="login.php">
<input type="text" name="email">
<input type="password" name="pass">
<input type="submit" name="submit" value="Log in" onclick="submitFunction()">
</form>


When the form is submitted I am checking if the username and password are correct

if(isset($_POST['submit'])) {
$email = $_POST['email'];
$pass = $_POST['pass'];

$sql = "SELECT email,password FROM user_details WHERE email='$email' AND password='$pass'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
$_SESSION["email"] = $_POST['email'];
}
else {
echo "Incorrect username or password. Please try again!";
}
}


But I also want to load a new page, which I am trying to do via javascript

function submitFunction()
{
window.location.href = "new url";
}


I tried replacing the submit button with just a button however then I can not get my php to execute because I can't use if(isset($_POST['submit'])), but if I use a submit button then I do not know how to call my javascript function because I can't use onclick can I? Any help would be appreciated :)

Also I know I should not just store the password in my database and sql injection and all that but I just want to try and get this to work

Answer

You can just load the new page with PHP after you check the login. Unless you have some other reason you need to do it with JavaScript, I think it makes more sense to do it in PHP anyway, because you'll want to do different things depending on whether or not the login was successful.

if ($result->num_rows > 0) {
    $_SESSION["email"] = $_POST['email'];
    header('Location: new url');
    exit;
}
else {      
    echo "Incorrect username or password. Please try again!";
}