skip to Main Content

I’m trying to do some kind of live search with ajax to show a list of users while typing in a search bar.
I’m struggling to return the data and display it in my view.

what I’ve tried so far:

My JQuery script:

$(document).ready(function (){
        const base_url = '<?php echo base_url();?>';
        $("#search_user").keyup(function (e){
            e.preventDefault();
            const val = $(this).value;
            $.ajax({
                type: "POST",
                url: base_url + "/public/Friendcontroller/search", // the method we are calling
                data: {search:val},
                dataType: "json",
                success: function (result) {
                    response(result);
                    console.log("Success",result);
                },
                error: function (result) {
                    console.error("unsuccessful",result);
                }
            });
        });
});

My controller function and model function:

Controller search function

public function search(): array
    {
       return $this->friend_model->liveSearch($_POST['search']);
    }

Model function

public function liveSearch($val) {
        $search = array();
        $result = $val;

        $getUser = "SELECT * FROM users WHERE userName LIKE '%$result%' OR firstName LIKE '%$result%'
                        OR lastName LIKE '%$result%'";

        $query = $this->db->query($getUser);

        foreach ($query->getResult() as $row) {
            $userID = $row->userID;
            $firstName = $row->firstName;
            $lastName = $row->lastName;
            $userName = $row->userName;
            $avatar = $row->avatarUrl;
            array_push($search, array('userID' => $userID, 'firstName' => $firstName,
                'lastName' => $lastName, 'userName' => $userName, 'avatarUrl' => $avatar));
        }
        return $search;
    }

The HTML where I want to render the results:

<div style="height: 32px"></div>
    <?php foreach (//Result from AJAX call here): ?>
        <div class="tabs-stage">
            <div class="container">
                <div class="person">
                    <div class="personHead">
                        <div class="profile">
                            <img id="avatar" class="head3" src="<?=base_url()?>/public/uploads/avatars/<?=$result['avatarUrl']?>">
                        </div>
                        <div class="personName">
                            <h2><?= $result['userName'] ?></h2>
                            <h4><?= $result['firstName'] . " " . $result['lastName'] ?></h4>
                        </div>
                    </div>
                </div>
            </div>
        </div>

2

Answers


  1. I think you should either return the array json encoded or "build" and return an html string to append it where ever you want on success

    If you return an html string then you can do this on success

    success: function (result) {
                    $("your div").html(result);
                    console.log("Success",result);
                }
    

    If you return json return json_encode($search); then you must iterate over each row and create/append the elements you want.

    Login or Signup to reply.
  2. You cant use php in the html anymore because it already has been run serverside,

    you have to rebuild the html with javascript, something like:

    success: function (result) {
        var $container = $('#resultContainer');
        $.each(result,function(i,res){
            $container.append('<div class="person"><h2>'+res.userName+'</h2></div>');
        });
    },
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search