0

I have a simple suggestion box, or kind of, but it is getting results twice depending of the user's typing speed. I guess it is because the previous ajax call has not finished yet.

I think I found an answer to my question here, but I really don't know how to implement the abort() function to cancel the previous call in my code.

class @Customer

  @find: (search_box) ->

    search = search_box.val()
    linked = if search_box.data('linked_list') then true else false
    list = $('#customers_search_list')
    list.empty()

    if search.length > 2

      $.ajax

        url: '/customers/find.json?search='+search

        beforeSend: ->
          search_box.addClass 'on_request'

        error: (error) ->
          Ui.live_notice i18n.user.error + ": \r\n "+error.errorThrown, 'error'

        success: (customers) ->
          for customer in customers
            list.append Customer.build_list_item customer, linked

        complete: ->
          search_box.removeClass 'on_request'

  @build_list_item: (customer, linked) ->

    [open_tag,close_tag] = ''
    [open_tag,close_tag] = ["<a href='/customers/#{customer.id}'>", "</a>"] if linked

    """
    <li>
      #{open_tag}
        <div class='names'>
          <div class='name'>#{customer.name}</div>
          <div class='fiscal_name'>#{customer.fiscal_name}</div>
        </div>
        <div class='code'>#{customer.code}</div>
      #{close_tag}
    </li>
    """

$(document).on "keyup", "input#customer_name_search", (el) =>
  Customer.find $(el.currentTarget)
pzin
  • 4,200
  • 2
  • 28
  • 49

1 Answers1

0

When faced with such issues, I usually like to throttle the request by waiting for 50-100 milliseconds after the keypress to see if a new keypress follows, and only then make the request. This can save a bit of load of your server as well. Try googling for "request throttling javascript" if you would like to see different approaches on how to implement this.

Emil Roman
  • 66
  • 4