Confused on jquery .ajax .done() function

前端 未结 3 546
无人及你
无人及你 2021-02-08 03:29

I\'m a bit confused on how to use the ajax .done() function. I\'m working on validating a form to check if a user exists in database and though ajax would be the best approach (

相关标签:
3条回答
  • 2021-02-08 04:01

    I think it should be result == 'true' as the result is a data string

    I just checked, I am correct, the quotes make it work

    PHP:

    <?php
    
    if($_POST['username']=='sambob'){echo 'true';}else{echo 'false';}
    
    ?>
    

    Javascript

    username='sambob';
    
    $(".check").blur(function(){
      $.post("validateUser.php", { username: username })
      .done(function(data) {
         if (data == 'true'){
            alert("User exists");
         }else{
            alert("User doesn't exist"); 
         }
      });
    });
    

    json PHP

    <?php
    
    if($_POST['username']=='sambob'){echo'{"exists":true}';}
                                else{echo'{"exists":false}';}
    ?>
    

    json Javascript

    $(".check").blur(function(){
       $.post("validateUser.php", { username : username },
       function(user){
          if (user.exists == true){
             alert("User exists");
          }else{
             alert("User doesn't exist");
          }
       }, "json");
    });
    
    0 讨论(0)
  • 2021-02-08 04:17

    Success: It will return the XHR success status, eg: 200
    Done: Once XHR get success then it will complete the and return with a return data

    Try below code

     $.ajax({
    type: "POST",
    url: Url,
    data: dataParameter,
    async: true,
    success: function(results, textStatus) {
        debugger;
        console.log("success : " + results);
    },
    error: function(xhr, status, error)
    {
        console.log("error : " + xhr.responseText);                   
    }
    }).done(function(results) {
        debugger;          
        console.log("done : " + results);           
    });
    
    0 讨论(0)
  • 2021-02-08 04:18

    On your php side, you should echo some json string, for example I'll do like this on the validateUser.php :

    //Check your database etc.
    $user_exists = array('error'=>false,'user'=>true);
    echo json_encode($user_exists);
    

    And than with jQuery :

    $.ajax({
        url: "validateUser.php",
        type: "post",
        data: "username= " + username,
        dataType: "json",
      }).done(function(result){
        if (result.error == false){
            //No errors, check user
            if(result.user == true)
                alert("Exists"); //now do some stuff
            else
                alert("User don't exists");
        }else{
          // There is an error
        }
      });
    
    0 讨论(0)
提交回复
热议问题