Home >>Codeigniter Tutorial >Username availability check using Codeigniter and AJAX
In this tutorial You will learn "Check username availability using Codeigniter Ajax and Mysql".
Sometimes, We want to check username availability instantly before the submit button and after entering of username field. In this case "check username availability using Codeigniter, AJAX and MySQL" technique is very helpful.
Save "Ajaxform.php" inside view folder
<!DOCTYPE html> <html lang="en"> <head> <title>Username availability check using Codeigniter, AJAX and MySQL</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body> <div class="container"> <h3 class="text-center text-primary">Username availability check using Codeigniter, AJAX </h3> <div class="form-group"> <label for="email">Enter Your Name:</label> <input type="text" class="form-control" id="name" placeholder="Enter Name" name="name"> </div> <div class="form-group"> <label for="email">Enter Your Email:</label> <input type="email" class="form-control" id="email" placeholder="Enter Email" name="email"> <label id="msg"></label> </div> <div class="form-group"> <label for="email">Enter Your Course:</label> <input type="text" class="form-control" id="course" placeholder="Enter course" name="course"> </div> <input type="button" class="btn btn-primary" value="save data" id="butsave"> </div> <script type="text/javascript"> // Ajax post $(document).ready(function() { $("#email").blur(function() { var email = $('#email').val(); if(email!="") { jQuery.ajax({ type: "POST", url: "<?php echo base_url('/index.php/AjaxController/checkUser'); ?>", dataType: 'html', data: {email: email}, success: function(res) { if(res==1) { $("#msg").css({"color":"red"}); $("#msg").html("This user already exists"); } else { $("#msg").css({"color":"green"}); $("#msg").html("Congrates username available !"); } }, error:function() { alert('some error'); } }); } else { alert("pls enter your email id "); } }); }); </script> </body> </html>
Save "AjaxController.php" inside controller folder
<?php class AjaxController extends CI_Controller { public function index() { $this->load->view('Ajaxform'); } public function checkUser() { $email=$this->input->post('email'); $this->load->model('AjaxModel'); $result=$this->AjaxModel->checkuser($email); if($result) { echo 1; } else { echo 0; } } } ?>
Save "AjaxModel.php" inside Model folder
<?php class AjaxModel extends CI_Model { public function checkuser($email) { $this->db->where('email',$email); $query=$this->db->get('student'); if($query->num_rows()>0) { return 1; } else { return 0; } } } ?>
Total Downloads : 77
Login / Register To Download