0

My Ajax function does not return any result

<div id="container">                
    <div id="connexion">
        <form  method="post" action="">
            <input type="text" id="login">
            <input type="password" id="password"><br />
            <input name="Submit" type="submit" id="ok" value="OK" class="btn "><br /><br />
            <span id="errormess"></span>
        </form >
    </div>
</div>
$(document).ready(function(){
    $("#ok").click(function() {
        var login = $("#login").val();
        var password = $("#password").val();
        var dataString = 'login='+ login + '&password=' + password;
        $.ajax({ 
            type: "POST",
            url: 'login.php',
            data: dataString,
            dataType: "json",
            success: function(data) {
                if (data == 0) {
                    $('#errormess').html("problem");
                } else { 
                    $('#errormess').html(data);
                }   
            }//success
        });//ajax
        return false;
    });//ok
});//document
$sql = "SELECT * FROM utilisateurs WHERE login ='$login' AND password=$password'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $userId= $row["id"];
        $today=time();
        $week=strftime('%W',$today) ;
    }
    $arr = array(
        'userId' => $userId,
        'week' => $week,   
     );
    echo json_encode($arr);       
}  
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • 1
    Change `;` to `;` – Max Apr 27 '16 at 10:32
  • @Max he isn't listening for submit event nor is preventing it, it will reload the page and js will not execute – Stack learner Apr 27 '16 at 10:33
  • 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 that 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 Apr 27 '16 at 12:41

3 Answers3

1

The issue is because the button click is submitting the form in the standard manner, meaning your AJAX request is prevented from completing. It's better practice to hook to the submit event of the form.

Also note that your PHP code will never return 0, it would be better to have a error handler should the AJAX not complete as expected. Finally, your current code is wide open to attack; you should look in to using SSL and using prepared statements to avoid SQL injection.

That said, here's a fix for your AJAX issues:

<div id="container">                
    <div id="connexion">
        <form id="myform" method="post" action="">
            <input type="text" id="login">
            <input type="password" id="password"><br />
            <input name="Submit" type="submit" id="ok" value="OK" class="btn "><br /><br />
            <span id="errormess"></span>
        </form>
    </div>
</div>
$("#myform").submit(function(e) {
    e.preventDefault(); // stop standard form submission

    $.ajax({ 
        type: "POST",
        url: 'login.php',
        data: {
            login: $("#login").val(),
            password: $("#password").val()
        },
        dataType: "json",
        success: function(data) {
            $('#errormess').html(data); 
        }
        error: function() {
            $('#errormess').html("problem");
        }
    });
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

I think you are giving the data parameter wrongly. It should be like

var dataString = {"login": login,
                   "password": password}

HTML

<div id="container">                
        <div id="connexion">
            <form  method="post" action="">
               <input type="text" id="login">
               <input type="password" id="password">
               <br />
        <input name="Submit" type="button" id="ok" value="OK" class="btn ">;      
               <br /> <br />
               <span id="errormess"></span>
           </form >
        </div>
    </div>

JS

$(document).ready(function(){
       $("#ok").click(function(e) {
              e.preventDefault();
              var login = $("#login").val();
              var password = $("#password").val();
              var dataString = {"login": login,
                   "password": password}
              $.ajax({ 
                  type: "POST",
                  url: 'login.php',
                  data: dataString,
                  dataType: "json",
                  success: function(data) {
                     if (data == 0) {
                            $('#errormess').html("problem");
                     } else { 
                            $('#errormess').html(data);
                     }   
                   }//success
                });//ajax
                return false;
            });//ok
     });//document

Also change the input type from submit to button and have and e.preventDefault() in your JS.

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
0

javascript code :

$(document).ready(function(){
        $("#ok").click(function(e) {
            e.preventDefault();
            var data = (this.form).serialize(); // added code 
            $.ajax({
                url: 'login.php',  
                data: data,   
                dataType:'json',  
                type:'POST',  
                async:false, 
                success: function(data) {       
                    if (data.success == 0) {  // added code 
                        $('#errormess').html("problem");
                    } else { 
                        $('#errormess').html(data);
                    }  
                },
                error: function(data) { // if error occured

                }
            });
        });//ok
    });//document

php code :

$sql = "SELECT * FROM utilisateurs WHERE login ='$login' AND    
 password=$password'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $userId = $row["id"];
        $today = time();
        $week = strftime('%W', $today);
    }
    $arr = array(
        'userId' => $userId,
        'week' => $week,
    );
    echo json_encode($arr);
} else {  // added code 
    $arr = array("success" => '0');
    echo json_encode($arr);
}

Please do check. I have modified the response from PHP as well as jquery code.

Parag Kuhikar
  • 485
  • 2
  • 6
  • 17