-1

I'm trying to make a simple Ajax call for a Bootstrap login modal. The main HTML code of the login Modal looks like this:

<form method="post" id="loginForm">
     <div id="loginMessage"></div>
     <div class="modal-footer">
       <button type="button" class="btn btn-success mr-auto"  data-target="#signupModal" data-toggle="modal" data-dismiss="modal">Register</button>
       <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
       <input class="btn" name="login" type="submit" id="inputButton" value="Login">                        
     </div>
 </form>

In case the whole HTML code for the modal would help : https://jsfiddle.net/aslah/hykxLqd5/2/

The jQuery code looks like this:

$('#loginForm').submit(function(event){
    //prevent default php processing
    event.preventDefault();
    //collect user inputs:
    var datatopost = $(this).serializeArray();
    //send the user data to login.php using AJAX
    $.ajax({
        url: "login.php",
        type : "POST",
        data : datatopost,
        success : function(data){
            if(data == 'success'){
                window.location = "mainpage.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 my login.php code :

<?php
   
//starting the session
session_start();
//connecting to database
include('connection.php');
//check user inputs
// DEFINE ERROR MESSAGES //
$missingEmail = '<p><strong>Please enter your email address!</strong></p>';
$missingPassword = '<p><strong>Please enter a password!</strong></p>';

// $email = $_POST["loginEmail"]
// $password = $_POST["loginPassword"]

if(empty($_POST["loginEmail"])){
    $error .= $missingEmail;
}else{
    $email = filter_var($_POST["loginEmail"], FILTER_SANITIZE_EMAIL);
}
if(empty($_POST["loginPassword"])){
    $error .= $missingPassword;
}else{
    $password = filter_var($_POST["loginPassword"], FILTER_SANITIZE_STRING);
}

//If there are any ERRORS
if($error){
    $resultMessage = '<div class="alert alert-danger">'. $error .'</div>' ;
    echo $resultMessage ;
}else{
    $email = mysqli_real_escape_string($link, $email);
    $password = mysqli_real_escape_string($link, $password);
    // $password = md5($password); no secure
    $password = hash('sha256', $password); 


    //check if the user is registered by matching EMAIL & PASSWORD
    $sql = "SELECT * FROM users WHERE email = '$email' AND password = '$password' AND activation='activated' ";
    $result = mysqli_query($link, $sql);

    //if any errors while running the query
    if(!$result){
        echo '<div class="alert alert-danger"> Error running the query!</div>';
        exit;
    }

    //if login failed print ERROR
    $count = mysqli_num_rows($result);
    if($count !== 1){
        echo '<div class="alert alert-danger">Wrong username or password</div>';
    }else{

        
        $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
        $_SESSION['user_id'] = $row['user_id'];
        $_SESSION['username'] = $row['username'];   
        $_SESSION['email'] = $row['email'];

        //if remember me is not checked
        if(empty($_POST['rememberme'])){
            echo "success";
            
        }else{
            // if rememberme is checked 
           
        }
    }
}
 
?> 

On submit of the the Login button I want to redirect the user to the mainpage.php. I tried all the different fixes I found here but nothing worked. I can't figure out what I'm doing wrong. Any help is highly appreciated.

This is what I get when I submit the form

  • One question: why are you using AJAX if your intention is to redirect afterwards? Why don't you make it a regular form submission and have PHP do all the work, including the redirect? – El_Vanja Mar 18 '21 at 15:44
  • Also, it would be helpful if you defined _"not working"_. Errors? Unexpected behaviour? Is the problem JS or PHP? Have you done any debugging you could share with us? – El_Vanja Mar 18 '21 at 15:46
  • Please add code for login.php as not sure how you are printing the response. – Amitabh Deotale Mar 18 '21 at 15:46
  • @El_Vanja yes, I just added a fiddle to my PHP code & the whole Login modal. I couldn't find a proper fiddle for PHP so pasted in the JS one. What I see when I submit the form is attached in the screenshot. – Aslah P Hussain Mar 18 '21 at 15:49
  • @AmitabhDeotale I just added my PHP code to the post! – Aslah P Hussain Mar 18 '21 at 15:51
  • Please share what **exactly** is not working, and what you've tried to resolve the problem. Is this a client-side problem (where the browser is not sending the request properly), or a server-side problem (where the properly generated request is not handled as expected)? – Nico Haase Mar 18 '21 at 15:54
  • 1
    The simplest and first step would be `console.log(data)` in the success handler. P.S. It took me three looks to actually find anything useful in that screenshot. Describing what happens would have been better (_"I see 'success' printed out as a message in the form"_). That word "success" just blends in with the rest. – El_Vanja Mar 18 '21 at 15:55
  • can you console.log(data) before if statement and check in developer tools what you get, as its strange , you get data as success so it should redirect. – Amitabh Deotale Mar 18 '21 at 15:56
  • Aside from all of that, please note that the way you build your queries is unsafe as it's open to [SQL injection](https://stackoverflow.com/questions/332365/how-does-the-sql-injection-from-the-bobby-tables-xkcd-comic-work). Use prepared statements to [prevent it](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). – El_Vanja Mar 18 '21 at 15:58
  • And also avoid using weak algorithms for password hashing (`sha` is better than `md5`, but still not good enough). PHP offers [built-in hashing functions](https://stackoverflow.com/questions/30279321/how-to-use-phps-password-hash-to-hash-and-verify-passwords) that are much safer. – El_Vanja Mar 18 '21 at 16:01
  • @NicoHaase the user is not being directed to the mainpage.php once login is submitted. It looks like the else block of Ajax call is being executed where it just prints (data) – Aslah P Hussain Mar 18 '21 at 16:04
  • @AmitabhDeotale I used console.log(data) & I get "success". – Aslah P Hussain Mar 18 '21 at 16:09

1 Answers1

0

Aslah P Hussain

I have tested your code. The first thing that caught my attention is Notice about the undefined variable $error. Possibly you have defined it in include('connection.php'); but if not, this can cause problems with PHP output that you are expecting.

Additionally, if you are 100% sure that the console returns the message success - you can change your check in JavaScript to:

if(data.indexOf('success') >= 0){
  window.location = "mainpage.php";
}else{
  $('#loginMessage').html(data);
}

Possibly not the best solution to the problem, but at least will show you that redirect is working

therceman
  • 231
  • 1
  • 6