CodeIgniter Laravel PHP Example Javascript jQuery MORE Videos New

Codeigniter 4 AJAX CRUD


<?php namespace App\Models;

use CodeIgniter\Model;

class ContactModel extends Model
{
    protected $table      = 'users';
    protected $primaryKey = 'id';
    protected $allowedFields = ['name', 'age', 'email'];
protected $useTimestamps = false;
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';
    protected $validationRules    = [];
    protected $validationMessages = [];
    protected $skipValidation     = false;
}

<?php namespace App\Controllers;

use CodeIgniter\Controller;
use App\Models\ContactModel;
class Contact extends BaseController
{
public function __construct(){
    }
public function index()
{
$data['title']   = "Contact List";

return view('view',$data);
}
public function view(){
$model = new ContactModel();
$data['posts'] = $model->findAll();
if($posts):
           foreach($posts as $post):
          echo '<tr>
             <td>'.$post["id"].'</td>
             <td>'.$post["name"].'</td>
             <td>'.$post["age"].'</td>
 <td>'.$post["email"].'</td>
            <td>
</tr>';

         
         endforeach;
        endif;
}
public function create()
{
$data['title']   = "Contact";
return view('contact',$data);
}
public function save(){
$data = $this->request->getVar();
$validation =  \Config\Services::validation();
$validation->setRules([
'name' => 'required|string',
'age' => 'required|integer|greater_than[0]',
'email' => 'required|valid_email'
]);
$res = $validation->withRequest($this->request)
->run();
if(!$res){

$data['title'] = "Contact";
echo view('contact',$data, [
'validation' => $validation
]);
}
else{
/*$contactModel = new \App\Models\ContactModel();*/
$session = \Config\Services::session();
try{
$model = new ContactModel();
$user=$model->insert($data);
/*$session->setFlashdata('msg', 'Record Inserted successfully');*/
echo "Record Inserted successfully";
}
catch(\Exception $e){
$session->setFlashdata('msg', 'Something went wrong');
}
$data['title'] = "Contact";
/*return redirect()->to( base_url('contact/index') );*/
}
}
public function view_edit($id = null)
    {
$model = new ContactModel();
$data['user'] = $model->where('id', $id)->first();
return view('update', $data);
    }
public function update($id = null){
$data = $this->request->getVar();
$id = $this->request->getVar('id');
$validation =  \Config\Services::validation();
$validation->setRules([
'name' => 'required|string',
'age' => 'required|integer|greater_than[0]',
'email' => 'required|valid_email'
]);
$res = $validation->withRequest($this->request)
->run();
if(!$res){

$data['title'] = "Contact";
echo view('contact',$data, [
'validation' => $validation
]);
}
else{
/*$contactModel = new \App\Models\ContactModel();*/
$session = \Config\Services::session();
try{
$model = new ContactModel();
$user=$model->update($id,$data);
echo 'Record Updated successfully';
}
catch(\Exception $e){
$session->setFlashdata('msg', 'Something went wrong');
}
$data['title'] = "Contact";
/*eturn redirect()->to( base_url('contact/index') );*/
}
}
public function delete(){
$id = $this->request->getVar('id');
$model = new ContactModel();
$data['user'] = $model->where('id', $id)->delete();
echo json_encode(array(
"statusCode"=>200
));
    }

contact.php

<!doctype html>
<html lang="en">
  <head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Codeigniter 4 CRUD Tutorial -  posts List Example - Expertphp.in</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css">
</head>
<body>
 <div class="container mt-4">
    <div class="register-box col-md-4">

<div class="alert alert-success" style="display:none;">
<strong>Success!</strong> <span id="success"></span>
</div>
<form method="post" id="form-data">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" name="name" class="form-control" placeholder="Enter Name" id="name">
</div>
<div class="form-group">
<label for="age">Age:</label>
<input type="number" name="age" class="form-control" placeholder="Enter Age" id="age">
</div>
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" name="email" class="form-control" placeholder="Enter email" id="email">
</div>
<button type="button" id="save" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script>
$(document).on('click','#save',function(e) {
    var data = $("#form-data").serialize();
    $.ajax({
         data: data,
         type: "post",
         url: "<?= base_url() ?>/Contact/save",
         success: function(data){
$('.alert-success').show();
            $("#success").text(data);
$("input").val("");
         }
});
});
</script>
</body>
</html>

view.php

<!doctype html>
<html lang="en">
  <head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Codeigniter 4 CRUD Tutorial -  posts List Example - Expertphp.in</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css">
</head>
<body>
<div class="container mt-6">
    <a href="<?php echo base_url('contact/create') ?>" class="btn btn-sm btn-success">Create</a>
   
  <div class="row mt-3">
     <table class="table table-bordered" id="posts">
       <thead>
          <tr>
             <th>Id</th>
             <th>Name</th>
             <th>Age</th>
             <th>Email</th>
  <th>Action</th>
          </tr>
       </thead>
       <tbody id="table_data">
 
         
       </tbody>
     </table>
  </div>
</div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js" type="text/javascript"></script>
 <script>
    $(document).ready( function () {
$.ajax({
url: "<?php echo base_url(); ?>/contact/view?>",
type: "POST",
cache: false,
data:{

},
success: function(dataResult){
alert(dataResult);
$("#table_data").html(dataResult);
}
});
$('#posts').DataTable();
$(document).on("click", ".delete", function() {

   var $ele = $(this).parent().parent();
$.ajax({
url: "<?php echo base_url(); ?>/contact/delete/<?php echo $post['id']; ?>",
type: "POST",
cache: false,
data:{
type: 2,
id: $(this).attr("data-id")
},
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode==200){
$ele.fadeOut().remove();
}
}
});
   });
 
    }
 
 
  );
</script>
</body>
</html>