'Using Ajax & PHP on same page, appending full page content again and again

I want to use ajax and PHP on the same page. For that I have removed the url paramter of ajax. Now when I am typing in the textbox, it is giving me desired results but it is appending a new page with all the elements inside the #check-username. I don't know why it is appending new textbox. Please take a look at my code.

<?php
global $wpdb; 
if(!empty($_POST["username"])) {
  $query = $wpdb->get_var("SELECT COUNT(*) FROM users WHERE username='" . $_POST["username"] . "'");
    ob_clean();
  if($query>0) {
    echo "<span style='color:red'> Sorry User already exists .</span>";
  }else{
    echo "<span style='color:green'> User available for Registration .</span>";
  }
}
?>

<span id="check-username"></span>
<label class="form-label" for="username">Username</label>
<input type="text" name="username" id="username" class="form-control"/>
                
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
  $('#username').on('input', function() {
    jQuery.ajax({
    data:'username='+$(this).val(),
    type: "POST",
    success:function(data){
        $("#check-username").html(data);
    },
    error:function (){}
    });
  });
});
</script>


Solution 1:[1]

exit; and using isset instead of !empty, solved all the problems. Thanks to @M. Eriksson

<?php
global $wpdb; 
if(isset($_POST["username"])) {
  $query = $wpdb->get_var("SELECT COUNT(*) FROM users WHERE username='" . $_POST["username"] . "'");
    ob_clean();
  if($query>0) {
    echo "<style>#username{border: 3px solid green;}</style>"; 
  }else{
    echo "<style>#username{border: 3px solid red;}</style>"; 
  }
exit;
}
?>

<span id="check-username"></span>
<label class="form-label" for="username">Username</label>
<input type="text" name="username" id="username" class="form-control"/>
                
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
  $('#username').on('input', function() {
    jQuery.ajax({
    data:'username='+$(this).val(),
    type: "POST",
    success:function(data){
        $("#check-username").html(data);
    },
    error:function (){}
    });
});});
</script>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1