-2

I'm making a dynamic PHP page with MySQL that has users log in. I recently changed the login, to jQuery/AJAX to make it more smooth and not lose the current page users are in. The thing is that when I miss my log in credentials it doesn't how any message and I want it to do so.

Here is my form :

<form id="ajax-login-form" action="session/login.php" method="post" role="form" autocomplete="off">
                <div class="form-group">
                    <label for="username">Login</label>
                    <input type="text" name="u" id="username" tabindex="1" class="form-control" placeholder="Log in" value="" autocomplete="off">
                </div>

                <div class="form-group">
                    <label for="password">Password</label>
                    <input type="password" name="p" id="password" tabindex="2" class="form-control" placeholder="Password" autocomplete="off">
                </div>
                <div class="form-group">
                    <div class="row">
                        <div class="col-xs-5 pull-right">
                            <input type="submit" name="login-submit" id="login-submit" tabindex="4" class="form-control btn btn-success" value="Log In">
                        </div>
                    </div>
                </div>
            </form>

My jQuery/Ajax :

$(document).ready(function () {
//From insert
$("#login-submit").click(function () {
    var $form = $('#ajax-login-form');
    $form.submit(false);
    $.post($form.attr("action"), $form.serializeArray(), function (info) {
        $("#result").html(info)
    })
    location.reload();
});
});

And finally my php code

<?php
session_start();
$lig = mysql_connect("localhost", "root","") or
die ("Problema na ligação ao servidor MYSQL");
mysql_select_db("demo", $lig);

$u=$_REQUEST['u'];
$p=$_REQUEST['p'];

$sql="select numuti,nome,nomeutilizador,codtipo,reset from utilizadores where nomeutilizador='$u' and password=md5('$p')";
$res=mysql_query($sql);
if (mysql_num_rows($res) == 1)
{
    $lin = mysql_fetch_array($res, MYSQL_ASSOC);
        $_SESSION['user'] = $lin['nomeutilizador'];
        $_SESSION['nivel'] = $lin['codtipo'];
        $_SESSION['reset'] = $lin['reset'];
        //$_SESSION['foto']  = $lin['imagem'];
        $_SESSION['nome']  = $lin['nome'];
        $_SESSION['cod']= $lin['numuti'];
}else{
echo "<div class='alert alert-danger'>
            <strong><center>Login Inválido, Tente Novamente</center></strong>
            </div>";
}
?>

This is probably a duplicate question, but I couldn't find a reliable answer to my issue, I tried making the errors with divs as you can see in my login.php page.

halfer
  • 19,824
  • 17
  • 99
  • 186
Artiom A
  • 11
  • 1
  • 10
  • 1
    Your code is vulnerable to [**SQL injection**](https://en.wikipedia.org/wiki/SQL_injection) attacks. You should use [**mysqli**](https://secure.php.net/manual/en/mysqli.prepare.php) or [**PDO**](https://secure.php.net/manual/en/pdo.prepared-statements.php) prepared statements with bound parameters as described in [**this post**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). – Alex Howansky May 25 '17 at 16:53
  • 1
    MD5 is not sufficient for password hashing. Use [`password_hash()`](http://us3.php.net/manual/en/function.password-hash.php) and [`password_verify()`](http://us3.php.net/manual/en/function.password-verify.php) instead. – Alex Howansky May 25 '17 at 16:54
  • 1
    Don't use the `mysql_*` functions. They have been deprecated since v5.5 (Jun 2013) and removed since v7.0 (Dec 2015). Instead use the [**mysqli_***](https://secure.php.net/manual/en/book.mysqli.php) or [**PDO**](https://secure.php.net/manual/en/book.pdo.php) functions with [**prepared statements**](https://secure.php.net/manual/en/pdo.prepare.php) and [**bound parameters**](https://secure.php.net/manual/en/pdostatement.bindparam.php). – Alex Howansky May 25 '17 at 16:54
  • Please read [Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers?](https://meta.stackoverflow.com/q/326569) - the summary is that this is not an ideal way to address volunteers, and is probably counterproductive to obtaining answers. Please refrain from adding this to your questions. – halfer May 25 '17 at 16:59
  • What version of JQuery are you using? – garek007 May 25 '17 at 17:11
  • @AlexHowansky This is nothing big, this is a project for school, and this is what they use, thank you for the reference for future work, I just need the messages, I am aware of md5 hashing and mysql_* functions, The help I need is in the ajax... – Artiom A May 25 '17 at 17:14
  • @garek007 3.2.1 – Artiom A May 25 '17 at 17:16
  • Would be better if you could use version 2, might be more stable and/or compatible. Are you required to use the latest? – garek007 May 25 '17 at 17:17
  • @garek007 yes I am required to use the latest because of the functions I've used in other pages. – Artiom A May 26 '17 at 13:58

2 Answers2

0

try changing your post statement to this

$.post($form.attr("action"), $form.serializeArray(), function (info) {
        $("#result").html(info)
    }).fail(function(){
    alert("Login unsuccessful, please try again.");
});
garek007
  • 395
  • 4
  • 15
  • I thought the php was already failing? In any case you should be able to just break the syntax somewhere to return an error – garek007 May 26 '17 at 15:19
  • I tried it, but you sure this is jquery v3 because its not detecting the fail, and just redirects me to the form url, with a blank page.. and doesn't do nothing else. – Artiom A May 26 '17 at 15:25
  • That should trigger the error and should be valid, even for version 3. I think your php must not be failing. You can try to force failure using the answer from this post (return a status other than 200) https://stackoverflow.com/questions/4417690/return-errors-from-php-run-via-ajax – garek007 May 26 '17 at 15:43
0

Basics

If you are using old mysql_connect function vulnerable to SQL injections you do not need any other security .. your system will be permeable.

First you need to do is switch to better methods like PDO.

jQuery

I recommend to use submit() function instead of click() and ajax() instead of post() to better manipulation with data.

$(document).ready(function () {

  $('#ajax-login-form').submit(function(e) {
      var form = this;

      e.preventDefault();
      var username = $("#username").val();
      var password = $("#password").val();

      $.ajax({
          type: 'POST',
          url: 'Your-login-url',
          data: {
              username: username,
              password: password
          },
          success: function(data) {
              // do your PHP login and echo 1 if authentication was successfull
              if(data === 1) {
                  form.submit();
              } else {
              // show alert or something that user has wrong credentials ...
                  $("#error_notif").show();
              }
          }
      });
  });

});

HTML

Another thing is error notification. I like to add error div right into the form or form container but set it as hidden. You can show it after jQuery Ajax ends with 0.

<div id="error_notif">You used wrong credentials.</div>

<style>
#error_notif {
   display:none;
}
</style>
  • I have only 1 issue, what do I have to import for that ajax to work, because my ajax does not work like that do not no why... it doesn't recognize `$('#ajax-login-form').submit(function(e) {` – Artiom A May 26 '17 at 09:11
  • jQuery v2 is required for this - `` – Dominik Vávra May 26 '17 at 13:07
  • I placed on the url `sessao/login.php` and I did the ecos, and when I it logs in I go to this blank page, it is not redirecting me back to where I was, could you help me also with this? by the way it goes to the `sessao/login.php` – Artiom A May 26 '17 at 13:57
  • This works, but it has an issue. When I enter the wrong login data it shows the error but when I reenter the correct data it won't submit and you need to reload the page. Any fix for this? – Mārcis Sep 27 '22 at 13:08