I'm using Codeigniter 4 and ajax to check if an username exists. It fails.
Here is the code that I used to check the username. I wanted a popup to show (available or not available) below the input box when the user is typing a username
AJAX
<script>
$(document).ready(function() {
$("#unameAkun").keyup(function() {
var username = $(this).val().trim();
if (username != '') {
$.ajax({
url: '<?php echo base_url('Dashboard_db/cek_username') ?>',
type: 'post',
data: {
username: username
},
success: function(response) {
$('#username_result').html(response);
}
});
} else {
$("#username_result").html("");
}
});
});
</script>
MODEL
public function cek_username($email_akun){
return $this->db->table('tabel_akun')->where(array('email_akun'=>$email_akun))->get()->getRowArray();}
CONTROLLER
public function cek_username() {
if (isset($_POST['unameAkun'])) {
$username = $_POST['unameAkun'];
$results = $this->Akun_->cek_username($username);
if ($results>0) {
$response = "<span style='color: red;'>Not Available.</span>";
} else {
$response = "<span style='color: green;'>Available.</span>";
}
}
echo $response;
}
right now you are querying for email instead of username, change your model to something like:
public function cek_username($username){
return $this->db ->table('tabel_akun')
->where(array('unameAkun'=>$username))
->get()
->countAllResults;
}
as you see, I've also changed getRowArray() into countAllResults(), as you want to return how often the username exists.
Further, I would use in the javascript part change
instead keyup
, so it only checks, once you have the full username (the event is deferred until the element loses focus) and not for each letter, but that's optional, as you like.