question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

autocompete with ajax

See original GitHub issue

Is possible use autocompete plugin with ajax? For data load from server, something like this (but not woking):

$.ajax({
    url: $this.attr('data-url'),
    method: 'post',
    data: {
         city: $this.val()
    },
    dataType: 'json',
   success: function (res) {
          if (res != false) {
                $this.autocomplete({
                     data: res
                });
          }
     }
});

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Reactions:6
  • Comments:29 (1 by maintainers)

github_iconTop GitHub Comments

7reactions
designosiscommented, Aug 26, 2016

I came up with something that works pretty great. It requires jquery.auto-complete.min.js and jquery.auto-complete.css from https://github.com/Pixabay/jQuery-autoComplete … which is beautifully coded, and only requires 3.4k.

Let’s say you want an autocompleted city search input that shows the city name but returns the city_id

HTML:

    <div class="row">
        <div class="input-field">
            <input type="hidden" id="city_id" name="city_id" value="">
            <input id="city_autocomplete" name="city_autocomplete" type="text">
            <label for="city_autocomplete">In which city do you live?</label>
        </div>
    </div>

(Note the hidden input. The code below modifies this value.)

JS:

    $('#city_autocomplete').autoComplete({
        source: function(term, response){
            $.getJSON('/path/to/search.php', { q: term }, function(data){ response(data); });
        },
        renderItem: function (item, search){
            // escape special characters
            search = search.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
            var re = new RegExp("(" + search.split(' ').join('|') + ")", "gi");
            return '<div class="autocomplete-suggestion" data-id="'+ item[0] +'" data-val="' + item[1] + '">' + item[1].replace(re, "<b>$1</b>") + '</div>';
        },
        onSelect: function(e, term, item){
            $('#city_id').val( item.data('id') );
        }
    });

(The renderItem is nearly identical to the default, just modified the return. If, like me, you will only ever do this kind of autocomplete, you can just replace that line in the source code, and omit the renderItem from the call above. With a bit more work, this could be modified to not require #id selectors in either JS or HTML.)

PHP:

    require '/path/to/requires.php';

    $res = [];
    $sql = $db->query("SELECT `id`,`name` FROM `cities` WHERE `name` LIKE '%". safeGET($_GET['q']) ."%' LIMIT 10");
    while ($r = $sql->fetch()) {
        $res[] = [$r['id'],$r['name']];
    }
    echo json_encode($res);

(Basically the PHP just outputs a JSON array like [[255,'New York'], [1261,'New Orleans'], [8212,'Newark'], ...]. Be sure to replace safeGET() with your own injection proofing methods.)

3reactions
dellertcommented, Feb 27, 2017
Read more comments on GitHub >

github_iconTop Results From Across the Web

jQuery AJAX Autocomplete – Country Example - Phppot
jQuery Autocomplete function is called on the key-up event of the input field. This function requests PHP for the list of countries via...
Read more >
jQuery autocomplete with callback ajax json - Stack Overflow
I'm trying to find a way to use jQuery autocomplete with callback source getting data via an ajax json object ...
Read more >
Autocomplete - jQuery UI
Autocomplete. Enables users to quickly find and select from a pre-populated list of values as they type, leveraging searching and filtering. Examples.
Read more >
Make Autocomplete Search with jQuery AJAX - Makitweb -
Autocomplete search filter display suggestion based on the user input e.g. listing all products which start with the character 'a'.
Read more >
Ajax Autocomplete for jQuery - GitHub
Ajax Autocomplete for jQuery allows you to easily create autocomplete/autosuggest boxes for text input fields. It has no dependencies other than jQuery.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found