简体   繁体   中英

Ajax does not return any result

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);       
}  

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");
        }
    });
});

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM