ummahusla
ummahusla

Reputation: 2063

Ajax/jQuery live search is duplicating the output results

I'm currently working on Ajax and jQuery live search which finds a results in a JSON file. Script is working fine, but the is only one problem - it's duplicating the result data.

EXAMPLE:

Results

MARKUP:

<div class="row">
  <h3>Live Search Results</h3>
  <div id="update-results">
  <p>event_name | club_name | memberid</p>
    <ul id="update">
      <!-- <li><a href="#"></a></li> -->
    </ul>
  </div>
</div>

SCRIPT:

$('#search').keyup(function() {
    var searchField = $('#search').val();
    var $update = $('#update');
    $update.empty();

    $.get("getEventsWithVideos.php?text=" + searchField, function(data) {
      var vals = jQuery.parseJSON(data);

        if($.isArray(vals['Event'])) {
          $.each(vals['Event'], function(k,v){
            $update.append("<li value='"+v['id']+"'><a href='#'>" + v['event_name'] + "</a></li>");
          });
        } else { 
            $update.append("<li value='"+vals['Event']['id']+"'><a href='#'>" + vals['Event']['event_name'] + "</a></li>");
        }

    });
});

I've tried to debug and stop the error, but it was unsuccessful. Can anyone help me please with that?

Upvotes: 1

Views: 1518

Answers (3)

Piotr Stapp
Piotr Stapp

Reputation: 19838

I didn't reproduce your error but I suspect that you have problem with multiple request to server and adding them all instead of last one. Probably adding below code will fix your problem

$update.empty();

Anyway I suggest you to use 2 more functions: throtlle and debounce from underscore to prevent too much request on every keyup.

Also you could try Rx.js witch give following example (https://github.com/Reactive-Extensions/RxJS):

var $input = $('#input'),
    $results = $('#results');

/* Only get the value from each key up */
var keyups = Rx.Observable.fromEvent($input, 'keyup')
  .map(function (e) {
    return e.target.value;
  })
  .filter(function (text) {
    return text.length > 2;
  });

/* Now debounce the input for 500ms */
var debounced = keyups
  .debounce(500 /* ms */);

/* Now get only distinct values, so we eliminate the arrows and other control characters */
var distinct = debounced
  .distinctUntilChanged();

Upvotes: 1

shiva kumar
shiva kumar

Reputation: 121

Try changing this line $update.empty(); of your code to $update.find('li').remove(); and put it inside the response handler.

This removes all the previous data before you append the new values. Hopefully it might work.

Upvotes: 0

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93631

Put the empty() inside the response handler:

$.get("getEventsWithVideos.php?text=" + searchField, function(data) {
     $update.empty();

basically you are clearing the list on every keystroke (rapid), then requesting the data, then (sometime later) appending the results that come back (which could be multiple results depending on the timing).

Upvotes: 4

Related Questions