Vince Vince - 12 days ago 5
Ajax Question

Confused on jquery .ajax .done() function

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 (still learning it). I have a php file that return true if user exists and false if user doesn't exist. How would I pass the boolean into the parameter for the done function?

$(".check").blur(function(){
var username = $(".check").val();
$.ajax({
url: "validateUser.php",
type: "post",
data: "username= " + username
}).done(function(result){
if (result == true){
// User exists
}else{
// User doesn't exist
}
});
});


I hope that made sense. I did my best to explain it.

Answer

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