Learn how to code in CodeIgniter part III

In the second part of this series, we learned how to send data to the server and save it in the database. In this tutorial, we are going to send data to the server via the jquery ajax method and save it in the database.

We are going to do it in four steps.

1.create a database.

2.create a form to send data to the server in application/views folder.

3.create a model to save data into the database in the application/models folder.

4.create a controller to handle form request and send the data to the model.

Step 1. same as tutorial 2 we are going to create a database where we will save user data.

CREATE TABLE `tbl_users` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `activation_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
, PRIMARY KEY (`user_id`));

Step 2. now we are going to create a view file called signup.php at application/views folder.

<html>

<head>

  <meta charset="utf-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="<?php echo base_url('assets/bootstrap/bootstrap.min.css');?>" rel="stylesheet">

  <title>
Login Example</title>

</head>

<body>

  <div class="card mt-3">

    <div class="card-body">

<div class="row justify-content-center">

	<div class="col-12 col-sm-6 col-md-6 col-lg-6 col-xl-6">

		<div class="card mx-5 my-5">

			<div class="card-body bg-secondary text-white font-weight-bold">

		<form autocomplete="off" action="<?php echo base_url('Signup/signup');?>" method="post"
		>

  <div class="form-group" >

    <label for="username">
User Name</label>

    <input type="text" class="form-control" id="username" aria-describedby="userlHelp"
    autocomplete="off">

    <small id="userHelp" class="form-text text-dark">
Please enter user name.</small>

  </div>

  <div class="form-group">

    <label for="password">
Password</label>

    <input type="password" class="form-control" id="password"  autocomplete="off">

    <small id="passHelp" class="form-text text-dark">
Please enter password.</small>

  </div>

  <button type="submit" id="login" class="d-inline btn btn-success">
Login</button>

 
</form>

</div>

</div>

	</div>

</div>

</div>

</div>

<script type="text/javascript" src="<?php echo base_url('js/jquery.min.js');?>">
</script>

<script type="text/javascript" src="<?php echo base_url('assets/bootstrap/js/popper.js');?>">
</script>

<script type="text/javascript" src="<?php echo base_url('assets/bootstrapjs//bootstrap.min.js');?>">
</script>

<script type="text/javascript" src="<?php echo base_url('js/jquery.toaster.js');?>">
</script>

<script>

  $(document).ready(function(){
  $("#login").on("click",function(event){
   event.preventDefault();
    if(!$.trim($("#username").val()).length)
    {
$("#tooltip-user").tooltip({"title":"this field is required"});
$("#username").css({"background-color":"aqua"}).focus();
      }
      else if(!$.trim($("#password").val()).length)
      {
$("#tooltip-pass").tooltip({"title":"this field is required"});
$("#password").css({"background-color":"aqua"}).focus();
      }
      else
      {
  $.ajax({
    url:"<?php echo base_url('Signup/signup_db');?>",
    type:"POST",
    data:{user:$("#username").val(),pass:$("#password").val()},
    success:function(data)
    {

    var res=$.parseJSON(data);
    if(res==="ok")
    {
alert(res);
window.open("http://localhost/yourproject/home","_self");
    }
    else
alert(data);
    }
    },
error:function(jxHr,msg,thrownerror)
    {
  alert(msg);
    }
        });
      }
    });
  });
  </script>

</body>

</html>

Step 3. Now we will create a model file in application/models folder.

class Signup_model extends CI_Model
{
  function __construct()
  {
  	parent::__construct();
  	$this->load->database();
  }
  public function check_login($username,$password)
  {
  $this->db->select("*");
  $this->db->where("username",$username);
  $this->db->password("password",$password);
  $res=$this->db->get("tbl_users");
  if($res->num_rows()>0)
  {
  return true;
  }
  else
  {
  return false;
  }
  }
  public function signup($username,$password)
  {
  if($this->check_login($username,$password)===false)
  {
  $data=array("username"=>$username,"password"=>$password);
       if($this->db->insert("tbl_users",$data))
       {
       	return TRUE;
       }
       else
       {
       	return FALSE;
       }
  }
  else
  {
  return false;
  }

  }
}

4. Now, at last, we will create a controller file at application/controllers folder.

<?

class Signup extends CI_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->load->model("Signup_model");
                $this->load->library("session");
	}
	public function signup()
	{
$this->load->view("signup",$data);
                
	}
	
	public function signup_db()
	{
		$username=$this->input->post("username",true);
		$password=$this->input->post("password",true);
		if((!empty($username))&&(!empty($password)))
		{
			if($this->Signup_model->signup($username,$password))
			{
				$res="ok";
                         $session["uid"]=base64_encode($username);
			}
			else
			{
				$res="error";
			}
		}
		else
		{
			$res="empty username or password";
		}
		echo json_encode($res);
	}
}
 ?>

 

Now we all done. If you go to http://yourdomain/Signup/signup      it will show a login form . After filling all detail if you submit the form then it will send data to server the login_check model function will check if the user exists or not. if not then signup model will enter the data to database and return a true value. after that controls return to the controller. if the response from the model function is true then it will send a response "ok" to the browser or it will send an error message to the browser.

previous

 

 

 

Other posts