0

I am trying to check user is exist from data using PHP and Ajax. Using the following codes:

Ajax

$('#btn_check_pc').click(function() {
  username = $("#username").val();
  $.ajax({
    type: 'POST',
    url: 'process.php',
    data: "username=" + username,
    dataType: 'json',
    beforeSend: function() { //Do Something    
    },
    success: function(response) {
      if (response == 'used') {
        console.log("Username Already In Use");
      }
    }
  });
});

PHP

<?php
    include_once "includes/get_data.php" ;

    $username = $_POST["username"];
    //Validating purchase

    $checkUserRegistered = mysqli_query($db,"SELECT  * FROM  users WHERE username = '$username'") or die(mysqli_error($db));

    if(!mysqli_num_rows($checkUserRegistered)){
        // Do Something
    }else{
         echo 'used';
    }
?>

So When I click the #btn_check_pc button then the PHP code will response used if the username already exists. I want to show it with console.log("Username Already In Use"), but it doesn't show. What I am missing here to show console.log() anyone can help me?

adeneo
  • 312,895
  • 29
  • 395
  • 388
AlwaysStudent
  • 1,354
  • 18
  • 49

2 Answers2

0

You have not use alert function so you can not see any alert box.

Your code is almost correct. If you want to see the result then use alert function in lieu of console.log() function inside success:function(response){} blcok.

just do comment the datatype: 'json' inside ajax. Otherwise you can use datatype:'text' .Reason is your expected data is not of json type. It is text type.

$('#btn_check_pc').click(function() {
  username = $("#username").val();
  $.ajax({
    type: 'POST',
    url: 'process.php',
    data: "username=" + username,
    // (alternative in case of data) data: {username:username},

    dataType: 'text',

   //(expected data is not json) dataType: 'json',
    beforeSend: function() { //Do Something    
    },
    success: function(response) {
      if (response == 'used') {
        console.log("Username Already In Use");
      }
    }
  });
});

Hope this will work.

Sadhon
  • 674
  • 7
  • 11
-1

You have to make two changes in your code.

First since you are using dataType json in your ajax call so you have to pass json in response from php

if(!mysqli_num_rows($checkUserRegistered)){
    echo json_encode(["success"=>false]);
}else{
    echo json_encode(["success"=>true]);
}

Second in JS. Since you are calling the ajax request via POST so you have to send data like the following.

$.ajax({
    ...
    data: {username: username}
    ...
});

Then in your success handler you can make a check like this

success: function(response) {
    if (response.success === true) {
        console.log("Username Already In Use");
    }
}