0

I am trying to use window.location = "userpage.php"; after a successful login but the page does not redirect. I am using Ajax and a modal form in my code

Everything works fine. I don't get any errors. I check the network headers. and there is no response in the network I have not been able to figure out the issue. I have tried

window.location.href

window.location.replace.

Nothing is working need help Thanks

This is part of the js file

    $("#loginform").submit(function(event) {
    //prevent default php processing
    event.preventDefault();
    //collect user inputs
    var datatopost = $(this).serializeArray();
    //send them to login.php using AJAX
      $.ajax({
      url: "login.php",
      type: "POST",
      data: datatopost,
      success: function(data) {
        if (data == "success") {
          window.location = "user_page.php";
        } else {
          $("#loginmessage").html(data);
        }
      },
      error: function() {
        $("#loginmessage").html(
          "<div class='alert alert-danger'>There was an error with the Ajax Call. Please try again later.</div>"
        );$
      }
    });
  });

This is part of my login.php file

//Start session
session_start();
//Connect to the database
include("connection.php");
...
$email = mysqli_real_escape_string($conn, $email);
$password = mysqli_real_escape_string($conn, $password);
$password = hash('sha256', $password);
    //Run query: Check combinaton of email & password exists
$sql = "SELECT * FROM users WHERE email='$email' AND password='$password' AND activation='activated'";
$result = mysqli_query($conn, $sql);
if (!$result) {
    echo '<div class="alert alert-danger">Error running the query!</div>';
    exit;
}
    //If email & password don't match print error
$count = mysqli_num_rows($result);
if ($count !== 1) {
    echo '<div class="alert alert-danger">Wrong Username or Password</div>';
} else {
//log the user in: Set session variables
    $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
    $_SESSION['user_id'] = $row['user_id'];
    $_SESSION['username'] = $row['username'];
    $_SESSION['email'] = $row['email'];

     if (empty($_POST['remember'])) {
         echo "success";
     } else {
  // todo logic for remember me 
}
}

This is the form modal

//Start session
session_start();
//Connect to the database
include("connection.php");
...
<form method="post" class="login_form modal" id="loginform">
  <div class="form-body">
    <div class="form-head"><h3>Login form</h3></div>
    <div class="form-logo"><img src="/dist/img/logo.svg" alt="" /></div>
    <div id="loginmessage"></div>
    <div class="form-inputs">
      <p><input type="email" name="email" placeholder="email" /></p>
      <p><input type="password" name="password" placeholder="Password" /></p>
    </div>
    <div class="login-session">
      <div class="remember">
        <input type="checkbox" id="remember" name="remember" value="remember" />
        <label for="remember">Remember me</label>
      </div>
      <div class="">
        <a href="#reset_password" rel="modal:open">Forgot my password</a>
      </div>
    </div>
    <div class="form-submit">
    <input class="btn btn-primary" type="submit" value="log in"/>
      <a class="btn btn-small" href="#signupform" rel="modal:open">register</a>
    </div>
  </div>
</form>
3
  • I don't see a session_start() in your PHP code? Also, you should use prepared statements to access your user database, and you should use password_hash and password_verify to store and test your passwords. Also you don't seem to be echoing success when your PHP succeeds, but that is what your ajax code is looking for. Commented Dec 23, 2018 at 5:09
  • @Nick this is just the part of the code i thought was worth posting. i have the session_start(); in all the files Commented Dec 23, 2018 at 5:16
  • 2
    I understand, but there isn't enough information to debug it. You could always add session_start(); then a ... at the top of your code to indicate that it is there. Most importantly though, since your ajax code is looking for the word success to enable redirection (which is your problem) it is important to see all the code that generates a response. Commented Dec 23, 2018 at 5:20

1 Answer 1

1

I finally found the solution to the issue.

In the index.js file:

success: function(data) {
   if (data == "success") {
      window.location = "user_page.php";` 

was changed to:

success: function(data) {
   if ($.trim(data) == "success") {
      window.location = "user_page.php";` 

Because the response message success for some reason had whitespace in it. I trimmed all whitespace and it worked.

Sign up to request clarification or add additional context in comments.

3 Comments

Does it continue to work with === instead of ==? It might be coercion, in which case it only appears to work and is introducing a bug that will be difficult to track down later.
@JeremyHarris yes I tried === and it works. So which is the better option according to you?
The ===, per the documentation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.