最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Autosuggestion JavascriptPHPAJAX Code - Stack Overflow

programmeradmin8浏览0评论

Consider an array holding some values

array = {'microsoft','micromax', 'miniclip','michael jackson','million','milky way'}

When an user start typing the text, say s/he is trying to enter million. When user start typing 'mi' the above suggestion in the array will be shown to the user.

My Question:

Let us assume user is typing the word 'mini clip', by typo s/he started to type 'mni' or 'minc' or 'nim' or 'imn' or 'nim' instead of 'min', this scenario also need to show the suggestion to the user. Becasue, anyway those typed characters are available in the word 'miniclip'. Typo is mon for all entry level users/mon users. So I need code in javascript/php/ajax/opensource library to suit this scenario.

Consider an array holding some values

array = {'microsoft','micromax', 'miniclip','michael jackson','million','milky way'}

When an user start typing the text, say s/he is trying to enter million. When user start typing 'mi' the above suggestion in the array will be shown to the user.

My Question:

Let us assume user is typing the word 'mini clip', by typo s/he started to type 'mni' or 'minc' or 'nim' or 'imn' or 'nim' instead of 'min', this scenario also need to show the suggestion to the user. Becasue, anyway those typed characters are available in the word 'miniclip'. Typo is mon for all entry level users/mon users. So I need code in javascript/php/ajax/opensource library to suit this scenario.

Share Improve this question edited Oct 25, 2013 at 10:08 Vinayagam asked Oct 25, 2013 at 10:02 VinayagamVinayagam 1,0021 gold badge10 silver badges29 bronze badges 11
  • You seriously need AJAX – Shankar Narayana Damodaran Commented Oct 25, 2013 at 10:04
  • Are you looking for an algo or is an out of the box solution also ok? If so, give solr a try wiki.apache/solr/Suggester – Dirk Lachowski Commented Oct 25, 2013 at 10:05
  • yes gentleman, we need AJAX – Vinayagam Commented Oct 25, 2013 at 10:05
  • Have a look here. stackoverflow./questions/18163775/… – Shankar Narayana Damodaran Commented Oct 25, 2013 at 10:11
  • But when an user started to type 'mni' or 'minc' or 'nim' or 'imn' or 'nim' instead of 'min' due to typo, this scenario also need to show the suggestion 'miniclip' to the user, that is my question. – Vinayagam Commented Oct 25, 2013 at 10:15
 |  Show 6 more ments

2 Answers 2

Reset to default 4

HTML

<form action=""><input type="text" name="word" id="word"></form>
<div id="auto"></div>

JS

$(function(){
    $('#word').keyup(function(e){
        var input = $(this).val();
        $.ajax({
            type: "get",
            url: "autoplete.php",
            data: {word: input},
            async: true,
            success: function(data){
                var outWords = $.parseJSON(data);
                $('#auto').html('');

                for(x = 0; x < outWords.length; x++){
                    $('#auto').prepend('<div>'+outWords[x]+'</div>'); //Fills the #auto div with the options
                }
            }
        })
    })
});

Don't forget to link jQuery...

<script src="http://ajax.googleapis./ajax/libs/jquery/1/jquery.min.js"></script>

N.B.

You would need to do something like add an onclick event to the child divs of #auto to replace the contents of #word (the input field).

PHP

$array  = array('microsoft','micromax', 'miniclip','michael jackson','million','milky way');
$input  = urldecode($_GET['word']); //Get input word/phrase (decode in case of spaces etc.)
$length = strlen($input);           //Get length of input word
// $min    = $length - 1;              //Length of word - 1
// $max    = $length + 1;              //Length of word + 1

$returned = preg_grep('/^(['.$input.']{'.$length.'}.*)$/i', $array); //Find matches in $array and return as array
$returned = array_values($returned);                                //Re-index from 0

echo json_encode($returned); //Returm json string to ajax call

Regex

/^([$input]{$length}.*)$/i
  1. / => Starting delimter
  2. ^ => Start of string
  3. ( => Start a capture group
  4. [ => Start a character class
  5. $input => Add the input word to the character class
  6. ] => End the character class (4)
  7. {$length} => Set length of string to match character class against (length of input word)
  8. .* => Match any following characters 0 or more times
  9. ) => End capture group (3)
  10. $ => Match end of string
  11. / => Ending delimeter
  12. i => Modifier for case insensitivity

Min/Max

I have included the mented $min and $max variables... An added feature that I thought you might like... You would implement them by changing:

{'.$length.'}          <-- Change this
{'.$min.','.$max.'}    <--To that
{'.$length.','.$max.'} <-- Or that (or another bination)

Example

An example might best show how this works...

Suppose an auto correct array of:

$array = array('loser', 'loses', 'losing');

and an input of:

lose

Currently ({'.$length.'}) the code will return:

loser
loses

But if you change it to {'.$min.','.$max.'} (and unment $min / $max); it will return:

losing
loser
loses

Try this one

Here is index.php

<html>
    <body>
        <input type="text" name="testid" id="testid" >
        <div id="result">

        </div>
    </body>
    <script src="https://code.jquery./jquery-1.12.0.min.js"></script>
    <script src="https://code.jquery./jquery-migrate-1.2.1.min.js"></script>
<script>
    $(document).ready(function(){
        var xhr = null;

        $('#testid').on("keyup", function(){
            if(xhr !== null) { 
                xhr.abort();
            }
            var searchkey = $(this).val();

           xhr = $.ajax({
            method: "POST",
            url: "ajax_request.php",
            data: { searchkey: searchkey }
          })
            .done(function( msg ) {
                $('#result').html(msg);
            });
        });

        $(document.body).on('click', ".listitem", function(e){
            var values = $(this).html();
            $('#testid').val(values);
            $('#result').html('');
            return false;
        });

    });
</script>
</html>

And this one is your ajax_request.php

<?php
$arr = array("Shailesh Sonare", "Hello World", "Hello Universe");

$html = "<ul>";

foreach ($arr as $key => $value) {
    $html .= "<li class='listitem'>" . $value . "</li>";
}

$html .= "</ul>";

echo $html;
发布评论

评论列表(0)

  1. 暂无评论