3

I have already created an auto-suggest box using AJAX and jQuery with PHP and postgreSQL with some help. I am still very new to AJAX and still learning the code as I go along. Luckily, the auto-suggest is working great, but I noticed that my up and down cursor keys for the keyboard are not working at all. Nothing happens when I arrow up or down in the suggested list. I am able to use the mouse to select in the suggested list, but cannot select things by use of keyboard arrows. What I want to do is change the keyup to keydown or add the keydown somewhere so this way it can go cross browser, and then move the selection in the required direction based on the keyCode. However I am still new to AJAX, and everytime I tried coding it, the suggested drop down list stops working or just crashes the page. I know it is in my ajax portion of the script. Shouldn't have anything much to do with the HTML or my php page. Any help getting the arrow keys to work along with the mouse is appreciated. Any code examples will be appreciated as well.

$(document).ready(function(){
    $("#search-box").keyup(function(){
        $.ajax({
            type: "POST",
            url: "autocomplete.php",
            data: 'keyword=' + $(this).val(),
            beforeSend: function() {
                $("#search-box").css("background", "#FFF url(LoaderIcon.gif) no-repeat 165px");
            },
            success: function(data){
                $("#suggesstion-box").show();
                $("#suggesstion-box").html(data);
                $("#search-box").css("background", "#FFF");
            }
        });
    });
});

function selectCountry(val) {
    $("#search-id").val(val);
    $("#suggesstion-box").hide();
}

function updateSearchBox(el) {
    $("#search-box").val($(el).html());   
}

Here is the HTML code for the search input in the form:

<div style="background-color:#ffffff; width:100%; float:left;  padding-bottom:25px; clear:both;  ">
    <div class="frmSearch " style="width:90%; float:left;"   >
        <label>                                             
            <input maxlength="75" type="search" name="jurisdiction_search"  class="search_keyword" id="search-box" placeholder="Enter County, City, or Client Name"  />
            <input type="hidden" name="search" id="search-id"  />
            <div class="box" id="suggesstion-box"></div>
        </label>                                                
    </div>
    <div style="width:10%; float:left; clear:right;">
        <label>                                         
            <input style="width:100%; height: 50px; " type="submit"  value="<?php echo esc_attr_x( 'Search', 'submit button' ) ?>" />
        </label>
    </div>
</div>

Here is some of the code in the autocomplete.php

<?php
if (!$result){
    echo "<div class='show' align='left'>No matching records.</div>";
}else {
?>
    <ul id="country-list" >
        <?php
        while($row=pg_fetch_assoc($result)){
        ?>                                      
            <li  onClick="selectCountry('<?php echo $row["id"]; ?>'); updateSearchBox(this);"> <?php echo "(".$row["id"].") ".$row["company"].", ".$row["st"]; ?> </li>
        <?php } ?>
    </ul>
<?php
}
?>

Here is my last failed attempt at working with ajax to get the arrow keys to work. Like I mention above, the suggested box stop working on this attempt.

<script>
$(document).ready(function(){
    $(document).on("keydown", function(e) {
        if (e.keyCode == 40) {
             if(chosen === "") {
                 chosen = 0;
             } else if((chosen+1) < $('#search-box').length) {
                chosen++;
             }
              $('#search-box').removeClass('selectedhash');
              $('#search-box:eq('+chosen+')').addClass('selectedhash');

               return false;
        }
        if (e.keyCode == 38) {
            if(chosen === "") {
                chosen = 0;
            } else if(chosen > 0) {
                chosen--;            
            }
            $('#search-box).removeClass('selectedhash');
            $('#search-box:eq('+chosen+')').addClass('selectedhash');
             return false;

        }
    });


    $("#search-box").live("keyup",function(e){
        $.ajax({
        type: "POST",
        url: "/VCSWeb/wp-content/themes/i-excel-child/autocomplete.php",
        data:'keyword='+$(this).val(),
        beforeSend: function(){
            $("#search-box").css("background","#FFF url(LoaderIcon.gif) no-repeat 165px");
        },
        success: function(data){
            $("#suggesstion-box ").show();
            $("#suggesstion-box").html(data);
            $("#search-box").css("background","#FFF");
        }
        });
    });
});

function selectCountry(val) {
  $("#search-id").val(val);
  $("#suggesstion-box").hide();
}

function updateSearchBox(el) {
  $("#search-box").val($(el).html());   
}

</script>

Again, very new to AJax and any help will be greatly appreciated.

ShadyNicNack
  • 107
  • 2
  • 14
  • You can use [jquery-ui autocomplete](https://jqueryui.com/autocomplete/#remote-jsonp) or [select2](https://select2.github.io/) it will save you a lot of time and a lot of bugs. – Mosh Feu Nov 01 '16 at 14:24
  • I am playing with the jquery-ui autocomplete, but it know seems that it wants to focus on chrome's memory autocomplete instead of the suggested autocomplete? – ShadyNicNack Nov 01 '16 at 14:38
  • $(document).ready(function(){ $("#search-box").keyup(function(){ $.ajax({ type: "POST", url: "/VCSWeb/wp-content/themes/i-excel-child/autocomplete.php", data:'keyword='+$(this).val(), beforeSend: function(){ $("#search-box").css("background","#FFF url(LoaderIcon.gif) no-repeat 165px"); }, success: function(data){ $("#suggesstion-box ").show(); $("#suggesstion-box").html(data); $("#search-box").css("background","#FFF"); } }).focus(function(){ $(this).data("autocomplete").search($(this).val()); }); }); }); – ShadyNicNack Nov 01 '16 at 14:54
  • added .focus(function(){ $(this).data("autocomplete").search($(this).val()); but, it wants to focus on chrome's memory autocomplete instead of the suggested autocomplete? – ShadyNicNack Nov 01 '16 at 14:54
  • I'm not sure I understand the problem. Can you create a [bin](http://jsbin.com) with the problem? Don't call to ajax, just hardcode some options. – Mosh Feu Nov 01 '16 at 15:04
  • https://jsfiddle.net/4oq87279/1/ Here is the ajax/ javascript in a fiddle. I have entered the autocomplete, but again, my autocomplete dropdown list disappeared and will not pull up... What am I doing wrong? – ShadyNicNack Nov 01 '16 at 15:59
  • I updated your fiddle: https://jsfiddle.net/rgj9Lxj6/1/, try it. Also, please, read the docs deeply. [see also](http://stackoverflow.com/a/21385958/863110) – Mosh Feu Nov 01 '16 at 16:32
  • Still no luck... Now my autocomplete list is not showing up when someone types. It seems when I have changed keyup to autocomplete and even add the source: function(request, response), my autocomplete is not showing up when someone types. I appologize but I am still learning AJAX. Could it be due to the focus: function(event,ui) or select: function(event, ui)??? – ShadyNicNack Nov 01 '16 at 16:57
  • GRRRR... Still no luck with either jquery-ui autocomplete or select2. How would I take the above code and put it in either autocomplete or select2 withouth crashing it. – ShadyNicNack Nov 01 '16 at 19:17
  • Mosh Feu: Can you show some code on what you mean on the autocomplete? Cannot seem to get it to work correctly? – ShadyNicNack Nov 01 '16 at 21:55
  • I was updated my fiddle. https://jsfiddle.net/rgj9Lxj6/2/. Doe I can't actually call an `ajax` request in jsfiddle, I [simulated it](http://doc.jsfiddle.net/use/echo.html). You can see that now it's working. In the `data` object you can see which format you should return from the server so it will works.' – Mosh Feu Nov 02 '16 at 08:55
  • unfortunately, it is still not working... I am think it is due to the autocomplete.php, which the Drop down was built as a un-ordered list "
  • '); updateSearchBox(this);">
  • " .... (See the PHP code above). It was not a Selection. So we need to set the focus on the un-ordered list and see about using the arrows and hitting return in he unorder list – ShadyNicNack Nov 02 '16 at 15:48
  • The autocomplete.php should returns a JSON, not an html. The JSON should be in the format just like in the fiddle. – Mosh Feu Nov 02 '16 at 16:03
  • Again new to the JSON scene... Here is my autocomplete.php code in a fiddle https://jsfiddle.net/zcsu78k0/ . Can you give me an example on how would I return a JSON using my php code and then popping it into the Ajax code? – ShadyNicNack Nov 02 '16 at 16:19
  • I'm not sure what is the function `pg_fetch_assoc` but if I understand correctly, you just need to return the object `$result` as JSON. You can do this by `echo json_encode($result)` [docs](http://php.net/manual/en/function.json-encode.php). Don't forget to set the `Content-Type` header to `application/json`. You can see the exact code in [this](http://stackoverflow.com/a/7064478/863110) answer. – Mosh Feu Nov 03 '16 at 07:59