skip to Main Content

So I am trying to work on a user authentication script for my database and on button click I would like to match the information in my mysql database to allow me to redirect to another page if its correct. But on a button click I get nothing happening at all. I can’t seem to figure out why. Whether the login information is correct or not, nothing seems to happen. Also I know about the password security etc, this is a trial run. I know its a risk. I should be using prepared statements, but this is just a test before I implement the rest.

HTML CODE

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Local Feedbacks</title>
  <link rel="stylesheet" 
      href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
  <link rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="assets/styles/styles.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <script>
         $(document).ready(function(){
    $('#submit').click(function(event){
      event.preventDefault();
      var username = $('#username').val();
      var pass = $('#password').val();
      $.ajax({
            url: 'login.php',
            method:'POST',
            data:
            {
                username: username,
                pass: pass,
                
            }
           
            
        });
        
    });
    
}); 
    </script>
  <!--Navigation Bar-->
    <nav class="navbar navbar-expand-sm navbar-dark bg-dark sticky-top">
        <h1 class="navbar-brand">Local Bands</h1>
        <button class="navbar-toggler" data-toggle="collapse" data-target="#navcollapse">
            <span class="navbar-toggler-icon"></span>
        </button>
        <!--Navigation Bar Options-->
        <div class="collapse navbar-collapse" id="navcollapse">
            <u1 class="navbar-nav mr-auto">
                <li class="nav-item">
                    <a class="nav-link" href="./index.html">Home</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="./assets/html/bands.html">Bands</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="./assets/html/contact.html">Contact Us</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="./assets/html/about.html">About</a>
                </li>
            </u1>
            <!--Search Button-->
            <form class="form-inline my-2 my-lg-0">
                <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
                <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
            </form>
            <!--Login section-->
            <u2 class="navbar-nav">
                <li class="nav-item">
                    <a class="nav-link" href="./assets/html/login.html">Login</a>
                </li>
            </u2>
        </div>
    </nav>

    <!--Title of the page-->
    <header class="main-header text-center text-black">
      <h1 class="login-text">Please Login</h1>
    </header>
    
    <main class="container">
      <div class="row">
          <!-- Form -->
          <form class="col-md-7" method="POST">
            
              <!-- Name -->
              <label for="name" class="mb-0 mt-1">Name</label>
              <input type="text" id="username" placeholder="Username" class="form-control" method="POST">
              <!-- Email -->
              <label for="password" class="mb-0 mt-1" method="POST">Password</label>
              <input type="text" id="password" placeholder="Password" class="form-control">
              <!-- Submit -->
              <input class="mt-1" type="submit" value="Log in" id="submit" target="_blank"> </input>
          </form>
          
      </div>
  </main>


</body>
</html>

PHP CODE

<?php
 ob_start();
 session_start();
  
$message="";
$dbname = 'project info';
$dbuser = 'root';
$dbpass = '';
$dbhost = 'localhost';


if(isset($_POST['username'])){
  $username = $_POST['username'];
}
if(isset($_POST['pass'])){
  $password = $_POST['pass'];
}



$conn= mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
  } 

  if(count($_POST)>0) {
    $result = mysqli_query($conn,"SELECT Username, pass FROM registration WHERE Username = '" . $_POST['username'] ."' AND pass = '" . $_POST['pass'] ."'");
    $count  = mysqli_num_rows($result);
    if($count==0) {
     $_SESSION['user'] = $_POST['username'];
     header("Location: http://localhost/index.html");
     
  }
  else{
    echo "Wrong info";
  }

  }
  
 $conn->close();
 ob_end_flush();
?>

2

Answers


  1. Works fine for me.

    Did you look at the devtool ? Type F12, and you will see in "Network" tab, that the request is well sent to "login.php"

    Login or Signup to reply.
  2. You should use submit() in jquery instead of click

    Note: that you have many syntax is not correct.

    On your ajax script

    $("#loginForm").submit(function(e) {
    
        e.preventDefault() // avoid to execute the actual submit of the form.
    
        const form = $(this)
        const url = form.attr('action')
        const method form.attr('method')
        
        $.ajax({
            type: method,
            url: url,
            data: form.serialize(), 
            success: function(response) {
               if(response.status) {
                  location.href = '/index.html'
               }
            }
    
        })
        
    })
    

    then on your form html

     <form id="loginForm" class="col-md-7" method="POST" action="login.php">
        <!-- Name -->
        <label for="name" class="mb-0 mt-1">Name</label>
        <input type="text" id="username" name="username" placeholder="Username" class="form-control">
        <!-- Email -->
        <label for="password" class="mb-0 mt-1">Password</label>
        <input type="password" id="password" name="password" placeholder="Password" class="form-control">
        <!-- Submit -->
        <input class="mt-1" type="submit" value="Log in" id="submit">
    </form>
    

    then in your login.php

    <?php
    
            session_start();
            
            $message="";
            $dbname = 'project info';
            $dbuser = 'root';
            $dbpass = '';
            $dbhost = 'localhost';
    
    
            if(isset($_POST['username']) && isset($_POST['password']) ){
                $username = $_POST['username'];
                $password = $_POST['password'];
            } else {
                die("Form is not defined");
            }
    
            $conn= mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
    
            if ($conn->connect_error) {
                die("Connection failed: " . $conn->connect_error);
            } 
    
            $username =  mysqli_real_escape_string($conn, $_POST['username']);
            $password =  mysqli_real_escape_string($conn, $_POST['password']);
    
            $result = mysqli_query($conn,"SELECT username FROM registration WHERE username = '" . $username ."' AND pass = '" . $password ."'");
            $count  = mysqli_num_rows($result);
    
            $status = false;
    
            if($count > 0 ) {
                $_SESSION['user'] = $username;
                $status = true;
            }
    
            echo json_encode(['status' => $status]);
            
            
            $conn->close();
     ?>
    

    Warning: You are wide open to SQL Injections and should use parameterized prepared statements instead of manually building your queries. They are provided by PDO or by MySQLi. Never trust any kind of input! Even when your queries are executed only by trusted users, you are still in risk of corrupting your data. Escaping is not enough!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search