Cara buat search ajax asynchronous dengan jQuery di CodeIgniter 4.
1. View Search
HTML :
<input type="text" class="form-control" placeholder="Cari" id="keyword" name="keyword">
JS :
function cariData() { let keyword = $('#keyword').val(); $.ajax({ type: "post", url: "/cari", data: { keyword: keyword }, dataType: "json", success: function(response) { if (response.data) { $('#result').html(response.data); } }, error: function(xhr, ajaxOptions, thrownError) { alert(xhr.status + '\n' + thrownError) } }); } $('#keyword').keyup(function() { cariData(); });
2. Controller
PHP :
public function cari() { $keyword = $this->request->getPost('keyword'); $data = $this->CheatsheetModel->cariData($keyword)->get(); if ($data != null) { $json = [ 'data' => view('visitor/hasil', [ 'cheatsheetdata' => $data ]) ]; echo json_encode($json); } }
3. Model
PHP :
public function cariData($keyword) { return $this->table('cheatsheet')->like('title', $keyword)->orlike('post', $keyword); }
4. View Hasil
PHP :
<?php foreach ($cheatsheetdata->getResultArray() as $cheatsheet) : ?> <div class="card overflow-hidden"> <div class="row"> <img src="<?= base_url() ?>/uploads/<?= $cheatsheet['image'] ?>" alt="" height="135px" width="240px"> <div class="col p-3"> <h3><?= $cheatsheet['title'] ?></h3> <p><?= $cheatsheet['excerpt'] ?></p> </div> </div> </div> <?php endforeach; ?>
Copyright © 2022. MFJRID.