2

I have a form in this index.html page with an Ajax script, on clicking the submit button it should just display "Authentification succeeded" or not, if the user is in the database, it works but when I hit submit it displays the message for only one second. How can I keep the message displayed? Here's the index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Accueil</title>
    <style type="text/css" media="screen">
        h1 {
            color:red;
        }
    </style>
        <script  language="javascript">
    function chargement()
    {
        var email = document.getElementById('email').value;
        var password = document.getElementById('password').value;

        var x = new XMLHttpRequest();
        x.open('GET','verif.php?email='+email+'&password='+password,true);
        x.onreadystatechange = function()
        {
            if ((x.readyState == 4 ) && (x.status == 200))
            {
                document.getElementById('res').innerHTML= x.responseText;
            }
        }
        x.send();
    }

    </script>
</head>
<body>
    <h1>Bienvenu(e) à Affariyet.tn </h1>
    <table>
    <form action="index.html" method="GET">
        <tr>
        <td>Email :</td>
        <td> <input type="text" id ="email" name="email" value="" placeholder="Votre Email"><br></td>
        </tr>
        <tr>
        <td>Mot De Passe : </td>
        <td><input type="password" id="password" name="password" value="" placeholder="Votre Mot De Passe"><br></td>
        </tr>
        <tr>
        <td></td>
        <td>
            <input type="submit" name="auth" value="S'authentifier" onclick="chargement()">
            <input type="reset" name="reset" value="Annuler">
        </td>
        </tr>
        <tr>
            <td></td>
            <td><div id="res"> </div></td>
        </tr>
    </form>

     </table>


</body>
</html>

And this is the PHP file that has the verification function :

<?php 
include 'config.php';
class main
{
    public $conn; 
    function __construct()
    {
        $c=new config();
        $this->conn=$c->connexion();
    }
    function verif($conn,$email,$password)
    {
        $req="SELECT `Email`,`Password` FROM utilisateur WHERE `Email`='$email' AND `Password`='$password' ";
        $res=$conn->query($req);
        return $res->RowCount();
    }
}

$m=new main();

$email=$_GET['email'];
$password=$_GET['password'];
$resultat=$m->verif($m->conn,$email,$password);
if($resultat==0)
{
    echo '<h4 style="color:red;"> Email ou mot de passe erroné</h4>';
}
else
{
    echo '<h4 style="color:green;">Authentification réussie. Accéder à la <a href=produit.php>Liste des produits</a></h4>';
}


 ?>
Hadh
  • 317
  • 1
  • 7
  • 22
  • You are open to SQL injections with this code. Currently the page reloads? – chris85 Jan 29 '16 at 01:32
  • ... also, you _relly_ should escape input, as as it is now, it's vulnerable to mysql injection. Look for `mysql_escape` and/or `prepared statement`s (preffered). – ankhzet Jan 29 '16 at 01:34
  • I'm open to way more than that hahah, I'm just testing out Ajax, and yes the page reloads, I just want it to keep diplaying the message without reloading? and how do I prevent sql injections? – Hadh Jan 29 '16 at 01:35
  • not to mention sending passwords over a GET. *Not safe*. – Funk Forty Niner Jan 29 '16 at 01:35
  • 1
    See http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php. – chris85 Jan 29 '16 at 01:36
  • I'm not posting this online or anything and using GET for passwords is stupid I know haha but again I'm just starting to test ajax – Hadh Jan 29 '16 at 01:36

2 Answers2

4

Your issue comes from that, when you submit:

  1. you execute the chargement() function as stated by the onclick attribute, and it works
  2. but since your button has type="submit" its default behaviour is to submit the form: then the action="index.php" is executed, so reloading the page, which obviously doesn't not include what you'd just put into the res div

To avoid this (i.e work without reloading the page) you can use two ways:

  • one is to prevent default action, either as already proposed by @anhkzet ( but in your case it can't work "as is"; look at it's answer's edit), or by adding event as argument to your chargement() function, then including event.preventDefault; before it ends

  • more simply you can change your <input type="submit"...> into <button type=button"...>: this way the form is not submitted at all.


EDIT in response to the supplemental question added by the OP in its comment below.

In order to use POST rather than GET you can merely substitute the desired method in your XMLHttpRequest.open() function.

I guess that you ask it because you're incertain about how to pass POST data in this case.
In fact there is no place in the method for an argument that would contain such data, but it doesn't matter: like with the <form> tag you can at once use POST method and keep query parameters attached to the url.

cFreed
  • 4,404
  • 1
  • 23
  • 33
  • Thank you so much! EDIT: do you know how can I use POST method instead of GET? – Hadh Jan 29 '16 at 01:55
  • @Hadh reagarding your last question, look at my edit. – cFreed Jan 29 '16 at 02:58
  • `which works with jQuery while you're using pure JS` - it _works_ with pure JS, I just forgot, that when handler specified in tag's attribute, you must explicitly specify, that you want use return value of substituted code as handler return value (i.e., `onclick="return handler()"`), 'cause by default handler attribute value if just treated as subject for `eval()`, without consideration of resulting return value. When you assigning handler directly in script (`...forms[0].onsubmit = handler;`, or via `addEventListener()`) - it will work `out of the box` without extra wrapping. – ankhzet Jan 29 '16 at 04:17
  • @ankhzet You're right, I initially reacted too quickly. Thanks for correcting me, I edited my answer. – cFreed Jan 29 '16 at 09:36
  • also `preventDefault()` wouldn't work, as it only prevents `bubbling` - event won't fire another attached handlers, but stil wouldn't prevent default behaviour of element reaction to event. So, other `onclick`'ed and `addEventListener()`'ed handlers wouldn't be called, but form would be submitted. – ankhzet Jan 29 '16 at 12:06
  • @ankhzet No, `preventDefault()` IS the way to avoid submit (the default action). You confused with `stopPropagation()`. – cFreed Jan 29 '16 at 12:45
  • Not quite, I just forget (_duh! again!_), that event object also must be passed explicitly, and was stumbled, when `preventDefault()` doesn't worked in test snippet... – ankhzet Jan 29 '16 at 13:15
2

Inputs with type submit are meant to send data in form to server. To prevent default behaviour of submit button add return false; at the end of chargement() handler.


Ok, apparantly, I forgot 'bout return statement inside attribute...

Either:

<input type="submit" onclick="return chargement()" />

... and add return false to the end of chargement method.

...or just

<input type="submit" onclick="chargement(); return false;" />

Both should work.

ankhzet
  • 2,517
  • 1
  • 24
  • 31