jQuery ajax keeps adding more and more elements

时间:2018-03-25 19:04:53

标签: javascript php jquery codeigniter

When a user searches for a username he gets results. When he backspaces or modifies the query, the results just keep getting added on top of the previous results instead of the results being modified and a fresh, updated result returned. I have modified the script here and there with no success yet.

My view:

<div class='container'>
    <div class='row'>
        <div class='col-sm-6 col-xs-12 col-centered'>
            <div class='panel panel-default'>
                <div class='panel-heading sticky'>
                    <div class='back pull-left'><a href='<?php echo site_url('chats') ?>'><span class='glyphicon glyphicon-chevron-left'></span></a></div>
                    <h1 class='panel-title text-center'>New Chat</h1>
                    <input class='form-control' id='search-field' type='text' placeholder='Username'>
                </div>
                <div class='panel-body'>
                    <ul class='users collapse'>
                    </ul>
                </div>
            </div>
        </div><!--end column-->
    </div><!--end row 1-->
</div><!--end container-->

My JS:

$(function() {
    var $search_field = $('#search-field');

    $search_field.on('keyup', searchByUsername);
    $search_field.focus();
});

function searchByUsername(e) {
    var username      = this.value.trim();
    var keyCode       = e.keyCode;
    var data          = {username : username};
    var $usersElement = $('.users');
    var users         = [];


    // Use this condition to prevent searching when whitespace is entered
    if (username) {
        var request = $.ajax({
            url      : site_url + 'search/searchByUsername/',
            method   : 'GET',
            data     : data,
            dataType : 'json'
        });

        request.done(function(jsonRepsonse) {

            if (jsonRepsonse) {
                var status        = jsonRepsonse.status;
                var usernames     = jsonRepsonse.usernames;

                if (status === 'success') {
                    $.each(usernames, function(index, value) {
                        // must be one line or will throw syntax error
                        users.push("<li class='user text-center'><a href='#'><span class='glyphicon glyphicon-user'></span><strong class='username'>" + value + "</strong></a></li>");
                    });console.log(users);

                    $usersElement
                        .append(users)
                        .show();

                }
            }
        });

        request.fail(function(xhr, status, error) {
            console.log(error);
        });
    }
    users.length = 0
    $usersElement.hide();
}

My Codeigniter controller function:

    public function searchByUsername()
    {   
        $username  = $this->input->get('username', true);
        $usernames = [];

        if (!empty($username)) {
            $usernames = $this->find_users_model
                            ->searchByUsername($username);
        }


        if (!empty($usernames)) {
            $this->jsonResponse(
                ['status'    => 'success',
                 'usernames' => $usernames]);

            return;
        }

        $this->jsonResponse(
                ['status' => 'success',
                 'usernames' => ['User not found']]);
    }

    private function jsonResponse($response)
    {
        $this->output
            ->set_status_header(200)
            ->set_content_type('application/json', 'utf-8')
            ->set_output(json_encode($response));
    }

Result:

enter image description here

1 个答案:

答案 0 :(得分:2)

This is your users container:

var $usersElement = $('.users');

On ajax response, you do:

$usersElement.append(users).show();

But you're always appending, never removing. Try emptying the element before populating it with users again:

$usersElement.empty().append(users).show();