0

I'm trying to implement a simple login form with an AJAX call that redirects to a page where I query the database I have and then redirect the user to the index page or back to the login page.

HTML:

<form method="post">
<h4> Please Login </h4>
    <input id="user" class="name" type="text" placeholder="Enter Username"/>
    <input id = "pass" class="pw" type="password" placeholder="Enter Password"/>
    <ul>
        <li><a href="#">Forgot your password?</a></li>
        <li><a href="#">Please Register Here</a></li>
    </ul>
    <input class="hvr-shrink" id="submitlogin" type="submit" value="Log in"/>
</form>

jQuery/AJAX:

$("#submitlogin").click(function() {
    var $username = document.getElementById("user").value;
    var $pass = document.getElementById("pass").value;
    $.ajax ({
        url: "login_request.php",
        type: "POST",
        data: {
           'username' : $username,
           'password' : $pass
        }
    });
});

login_request.php

 include "connect.php";
 $myusername = mysqli_real_escape_string($db,$_POST['username']);
 $mypassword = mysqli_real_escape_string($db,$_POST['password']); 

$sql = "SELECT username, password FROM `CGSB_Compliance`.`nd_users` WHERE username = '$myusername' AND password = '$mypassword'";
$result = mysqli_query($db, $sql);
$count = mysqli_num_rows($result);

if($count == 1){
    $_SESSION['user'] = $myusername;
    header("location:index.php");
} else {
    header("location:login.php");
}

I have a table with one username and password, and every time I login, it just refreshes the login page. I checked my code a few times now and I can't seem to find the reason as to why it's not working. I have a feeling it's a silly mistake on my part but I looked at lots of examples and they all have pretty much the same thing. Any help is appreciated.

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
ybce
  • 176
  • 4
  • 17
  • 1
    [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)*** Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! – Jay Blanchard Jun 30 '16 at 15:43
  • 1
    **Never store plain text passwords!** Please use PHP's [built-in functions](http://jayblanchard.net/proper_password_hashing_with_PHP.html) to handle password security. If you're using a PHP version less than 5.5 you can use the `password_hash()` [compatibility pack](https://github.com/ircmaxell/password_compat). Make sure you ***[don't escape passwords](http://stackoverflow.com/q/36628418/1011527)*** or use any other cleansing mechanism on them before hashing. Doing so *changes* the password and causes unnecessary additional coding. – Jay Blanchard Jun 30 '16 at 15:43
  • 3
    You're not doing anything to stop the form from reloading the page. You should use the developer console to see what's going on. Try changing the `type="submit"` to `type="button"` – j08691 Jun 30 '16 at 15:43
  • @j08691 I changed it to `button` but then form stopped submitting. The console is blank. I used it to check that I'm retrieving all the information correctly and I was. – ybce Jun 30 '16 at 15:47
  • 1
    @j08691 is talking about preventing the default submit event, for one. – Jay Blanchard Jun 30 '16 at 15:48
  • And changing the header in PHP sends nothing back to your AJAX call. You need to return some value and then have JavaScript do the redirection. – j08691 Jun 30 '16 at 15:50

2 Answers2

0

Hi I have tried your code the problem is that your ajax request not going to your login page. Also dont use $ sign in javascript variables use var or nothing. Also may be you have not call jQuery library.

I have tried this and run myself. Please try this one. Don't hesitate to mark it as your answer if you find your solution.

// download file and save in your file if you are not connected to net and include with correct path

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <Script>
    $(document).ready(function(){

    $("#postsubmit").click(function(e) {
        var pass = $("#pass").val();
         var username = $("#user").val();
            $.ajax({type:"POST",url:"login_request.php",data:{password:pass, username:username},
                    });
       });
    });
       </script>

    <h4> Please Login </h4>
    <form name="postcontent" >


        <input id="user" class="name" type="text" placeholder="Enter Username"/>
        <input id = "pass" class="pw" type="password" placeholder="Enter Password"/>
        <ul>
            <li><a href="#">Forgot your password?</a></li>
            <li><a href="#">Please Register Here</a></li>
        </ul>
         <input name="postsubmit" type="button" id="postsubmit" value="Sing Up"/>

     </form>

    login_request.php

    <?php
    $db = mysqli_connect('localhost','root','','yourdatabasename');
    echo $myusername = mysqli_real_escape_string($db,$_POST['username']);
     echo $mypassword = mysqli_real_escape_string($db,$_POST['password']);

    $sql = "SELECT username, pass FROM reg WHERE username = '$myusername' AND pass = '$mypassword'";
    $result = mysqli_query($db, $sql);
    $count = mysqli_num_rows($result);
    if($count == 1){
        $_SESSION['user'] = $myusername;
        header("location:index.php");
    } else {
        header("location:login.php");
    }

change your table name and datbase name according to yours.

Also add preventDefault() to restrict page refreshing

Passionate Coder
  • 7,154
  • 2
  • 19
  • 44
  • Thank you for the detailed answer, I shall try it now and let you know. I have jQuery loaded so that isn't an issue. – ybce Jul 04 '16 at 12:10
  • still not working, the page does nothing when I click the button. The button triggers the function but nothing happens. – ybce Jul 04 '16 at 12:38
-1

My friend I think your problem is in your jQuery/AJAX: put it on the bottom of the </body> tag or put it inside $(document).ready(function{});