Autocomplete

Hi,

I am working on this main page: https://kroweb.dk/gfdev/arkivalier/sognefakta/

It is the searchfield at the top I am trying to add an autocomplete function to.

So I have made this testpage: https://kroweb.dk/gfdev/arkivalier/sognefakta/autocomplete.php which is working nicely with autocomplete. Try to just put in an 'a' in the searchfield and you will see a nice list of suggestions below the field.

Then I try to include this working autocomplete page on the mainpage, like this
<?php include_once('autocomplete.php'); ?>

Open in new window

but then the autocomplete is not working on the main page. The form is working as supposed but the autocomplete is not working.

What am I doing wrong here :)
Peter KromanSales ExecutiveAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
You have included a full page inside your existing page - that is not what you want to do here.
Rather copy the code for the auto complete to the new page.
OR
create your autocomplete as a snippet rather than a full page - although I would not recommend this.

Here is what you should do
Copy this line to where you want it in your target page
<input id="search" type="text" name="sogn" placeholder="Søg pr. sogn">

Open in new window

Copy the following to the bottom of your target document
<script>
function autocomplete(inp, arr) {
  /*the autocomplete function takes two arguments,
  the text field element and an array of possible autocompleted values:*/
  var currentFocus;
  /*execute a function when someone writes in the text field:*/
  inp.addEventListener("input", function(e) {
      var a, b, i, val = this.value;
      /*close any already open lists of autocompleted values*/
      closeAllLists();
      if (!val) { return false;}
      currentFocus = -1;
      /*create a DIV element that will contain the items (values):*/
      a = document.createElement("DIV");
      a.setAttribute("id", this.id + "autocomplete-list");
      a.setAttribute("class", "autocomplete-items");
      /*append the DIV element as a child of the autocomplete container:*/
      this.parentNode.appendChild(a);
      /*for each item in the array...*/
      for (i = 0; i < arr.length; i++) {
        /*check if the item starts with the same letters as the text field value:*/
        if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
          /*create a DIV element for each matching element:*/
          b = document.createElement("DIV");
          /*make the matching letters bold:*/
          b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
          b.innerHTML += arr[i].substr(val.length);
          /*insert a input field that will hold the current array item's value:*/
          b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
          /*execute a function when someone clicks on the item value (DIV element):*/
          b.addEventListener("click", function(e) {
              /*insert the value for the autocomplete text field:*/
              inp.value = this.getElementsByTagName("input")[0].value;
              /*close the list of autocompleted values,
              (or any other open lists of autocompleted values:*/
              closeAllLists();
          });
          a.appendChild(b);
        }
      }
  });
  /*execute a function presses a key on the keyboard:*/
  inp.addEventListener("keydown", function(e) {
      var x = document.getElementById(this.id + "autocomplete-list");
      if (x) x = x.getElementsByTagName("div");
      if (e.keyCode == 40) {
        /*If the arrow DOWN key is pressed,
        increase the currentFocus variable:*/
        currentFocus++;
        /*and and make the current item more visible:*/
        addActive(x);
      } else if (e.keyCode == 38) { //up
        /*If the arrow UP key is pressed,
        decrease the currentFocus variable:*/
        currentFocus--;
        /*and and make the current item more visible:*/
        addActive(x);
      } else if (e.keyCode == 13) {
        /*If the ENTER key is pressed, prevent the form from being submitted,*/
        e.preventDefault();
        if (currentFocus > -1) {
          /*and simulate a click on the "active" item:*/
          if (x) x[currentFocus].click();
        }
      }
  });
  function addActive(x) {
    /*a function to classify an item as "active":*/
    if (!x) return false;
    /*start by removing the "active" class on all items:*/
    removeActive(x);
    if (currentFocus >= x.length) currentFocus = 0;
    if (currentFocus < 0) currentFocus = (x.length - 1);
    /*add class "autocomplete-active":*/
    x[currentFocus].classList.add("autocomplete-active");
  }
  function removeActive(x) {
    /*a function to remove the "active" class from all autocomplete items:*/
    for (var i = 0; i < x.length; i++) {
      x[i].classList.remove("autocomplete-active");
    }
  }
  function closeAllLists(elmnt) {
    /*close all autocomplete lists in the document,
    except the one passed as an argument:*/
    var x = document.getElementsByClassName("autocomplete-items");
    for (var i = 0; i < x.length; i++) {
      if (elmnt != x[i] && elmnt != inp) {
        x[i].parentNode.removeChild(x[i]);
      }
    }
  }
  /*execute a function when someone clicks in the document:*/
  document.addEventListener("click", function (e) {
      closeAllLists(e.target);
      });
}

/*An array containing all the country names in the world:*/
var parishes = ['Allinge','Bornholms Baptistkirke','Bodilsker','Christiansø','Hasle','Ibsker','Katolsk kirke','Klemensker','Knudsker','Neksø','Neksø - Methodist','Nyker','Nylarsker','Olsker','Pedersker','Povlsker','Rutsker','Rø','Rønne','Rønne og Allinge - Methodist','Sandvig','Svaneke','Vester Marie','Åker','Åkirkeby','Øster Larsker','Øster Marie','Alsønderup','Annisse','Asminderød','Birkerød','Bistrup','Blistrup ','Blovstrød','Dråby','Egebæksvang','Esbønderup','Farum','Ferslev','Frederiksborg Slotssogn','Frederikssund','Frederikssund og Ude Sundby','Frederiksværk','Ganløse','Gerlev','Gilleleje','Græse','Græsted','Grønholt','Gørløse','Hellebæk','Helsinge','Helsingør','Hillerød','Hornbæk','Humlebæk','Hørsholm','Jørlunde','Karlebo','Kregme','Krogstrup','Kyndby','Lille Lyngby','Lillerød','Lynge','Melby','Mårum','Nødebo','Nørre Herlev','Oppe Sundby','Præstevang','Ramløse','Selsø','Sigerlevvester','Skibby','Skuldelev','Skævinge','Slagslunde','Slangerup','Snostrup','Stenløse','Strø','Søborg','Tibirke','Tikøb','Tjæreby','Torup','Uggeløse','Usserød','Uvelse','Valby','Vejby','Veksø','Vellerup','Vinderød','Ølsted','Ølstykke','Agerskov','Aller','Bevtoft','Bjerning','Branderup','Christiansfeld',' Tyrstrup','Fjelstrup','Fole','Frørup','Gram','Grarup','Haderslev (Gammel Haderslev)','Haderslev - Vor Frue','Halk','Hammelev','Hjerndrup','Hjerting','Hoptrup','Hygum','Jegerup','Jels','Lintrup','Maugstrup','Moltrup','Nustrup','Oksenvad','Rødding','Skodborg','Skrave','Skrydstrup','Sommersted','Stepping','Sønder Starup','Tirslund','Toftlund','Vedsted','Vilstrup','Vojens','Vonsbæk','Åstrup','Øsby','Øster Lindet','Abildgård',];

/*initiate the autocomplete function on the "search" element, and pass along the parishes array as possible autocomplete values:*/
autocomplete(document.getElementById("search"), parishes);
</script>

Open in new window

Then copy your styling to the head
<style>
.autocomplete {
  /*the container must be positioned relative:*/
  position: relative;
  display: inline-block;
}
input {
  border: 1px solid transparent;
  background-color: #f1f1f1;
  padding: 10px;
  font-size: 16px;
}
input[type=text] {
  background-color: #f1f1f1;
  width: 100%;
}
input[type=submit] {
  background-color: DodgerBlue;
  color: #fff;
  cursor: pointer;
}
.autocomplete-items {
  position: absolute;
  border: none;
  border-bottom: none;
  border-top: none;
  z-index: 99;
  /*position the autocomplete items to be the same width as the container:*/
  top: 105%;
  left: 0;
  right: 0;
}
.autocomplete-items div {
  padding: 10px;
  cursor: pointer;
  background-color: #fff; 
  border-bottom: none; 
}
.autocomplete-items div:hover {
  /*when hovering an item:*/
  background-color: #e9e9e9; 
}
.autocomplete-active {
  /*when navigating through the items using the arrow keys:*/
  background-color: DodgerBlue !important; 
  color: #ffffff; 
}
</style>

Open in new window

I tested this and it does not work so well - any particular reason you chose this autocomplete over one of the more popular ones out there?

jQueryUI Autocomplete
Twitter Typeahead
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Peter KromanSales ExecutiveAuthor Commented:
I have tried your model. It is not working at all. I have also tried to create a snippet of the autocomplete file, and this still works when loading the snippet alone but not when loading it into the main document.

And - No the only reason I used this autocomplete is that this is the one I found first.
0
mohan singhWeb developerCommented:
Some time some library are creating a problem
so please check your library

Thank You
0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

Peter KromanSales ExecutiveAuthor Commented:
I have tried to remove all libraries one-bt-one. No difference.

The snippet works nicely as a stand alone, and it has no library bindings:
<style>
* {
  box-sizing: border-box;
}
body {
  font: 16px Arial;  
}
.autocomplete {
  /*the container must be positioned relative:*/
  position: relative;
  display: inline-block;
}
input {
  border: 1px solid transparent;
  background-color: #f1f1f1;
  padding: 10px;
  font-size: 16px;
}
input[type=text] {
  background-color: #f1f1f1;
  width: 100%;
}
input[type=submit] {
  background-color: DodgerBlue;
  color: #fff;
  cursor: pointer;
}
.autocomplete-items {
  position: absolute;
  border: none;
  border-bottom: none;
  border-top: none;
  z-index: 99;
  /*position the autocomplete items to be the same width as the container:*/
  top: 105%;
  left: 0;
  right: 0;
}
.autocomplete-items div {
  padding: 10px;
  cursor: pointer;
  background-color: #fff; 
  border-bottom: none; 
}
.autocomplete-items div:hover {
  /*when hovering an item:*/
  background-color: #e9e9e9; 
}
.autocomplete-active {
  /*when navigating through the items using the arrow keys:*/
  background-color: DodgerBlue !important; 
  color: #ffffff; 
}
</style>

<meta charset="UTF-8">

<!--Make sure the form has the autocomplete function switched off:-->
<form autocomplete="off" action="">
  <div class="autocomplete" style="width:300px;">
    <input id="search" type="text" name="sogn" placeholder="Søg pr. sogn">
  </div>
  <input type="submit" value="Søg">
  <!-- <button type="submit" class="btn btn-primary">Søg</button> -->
</form>

<script>
function autocomplete(inp, arr) {
  /*the autocomplete function takes two arguments,
  the text field element and an array of possible autocompleted values:*/
  var currentFocus;
  /*execute a function when someone writes in the text field:*/
  inp.addEventListener("input", function(e) {
      var a, b, i, val = this.value;
      /*close any already open lists of autocompleted values*/
      closeAllLists();
      if (!val) { return false;}
      currentFocus = -1;
      /*create a DIV element that will contain the items (values):*/
      a = document.createElement("DIV");
      a.setAttribute("id", this.id + "autocomplete-list");
      a.setAttribute("class", "autocomplete-items");
      /*append the DIV element as a child of the autocomplete container:*/
      this.parentNode.appendChild(a);
      /*for each item in the array...*/
      for (i = 0; i < arr.length; i++) {
        /*check if the item starts with the same letters as the text field value:*/
        if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
          /*create a DIV element for each matching element:*/
          b = document.createElement("DIV");
          /*make the matching letters bold:*/
          b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
          b.innerHTML += arr[i].substr(val.length);
          /*insert a input field that will hold the current array item's value:*/
          b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
          /*execute a function when someone clicks on the item value (DIV element):*/
          b.addEventListener("click", function(e) {
              /*insert the value for the autocomplete text field:*/
              inp.value = this.getElementsByTagName("input")[0].value;
              /*close the list of autocompleted values,
              (or any other open lists of autocompleted values:*/
              closeAllLists();
          });
          a.appendChild(b);
        }
      }
  });
  /*execute a function presses a key on the keyboard:*/
  inp.addEventListener("keydown", function(e) {
      var x = document.getElementById(this.id + "autocomplete-list");
      if (x) x = x.getElementsByTagName("div");
      if (e.keyCode == 40) {
        /*If the arrow DOWN key is pressed,
        increase the currentFocus variable:*/
        currentFocus++;
        /*and and make the current item more visible:*/
        addActive(x);
      } else if (e.keyCode == 38) { //up
        /*If the arrow UP key is pressed,
        decrease the currentFocus variable:*/
        currentFocus--;
        /*and and make the current item more visible:*/
        addActive(x);
      } else if (e.keyCode == 13) {
        /*If the ENTER key is pressed, prevent the form from being submitted,*/
        e.preventDefault();
        if (currentFocus > -1) {
          /*and simulate a click on the "active" item:*/
          if (x) x[currentFocus].click();
        }
      }
  });
  function addActive(x) {
    /*a function to classify an item as "active":*/
    if (!x) return false;
    /*start by removing the "active" class on all items:*/
    removeActive(x);
    if (currentFocus >= x.length) currentFocus = 0;
    if (currentFocus < 0) currentFocus = (x.length - 1);
    /*add class "autocomplete-active":*/
    x[currentFocus].classList.add("autocomplete-active");
  }
  function removeActive(x) {
    /*a function to remove the "active" class from all autocomplete items:*/
    for (var i = 0; i < x.length; i++) {
      x[i].classList.remove("autocomplete-active");
    }
  }
  function closeAllLists(elmnt) {
    /*close all autocomplete lists in the document,
    except the one passed as an argument:*/
    var x = document.getElementsByClassName("autocomplete-items");
    for (var i = 0; i < x.length; i++) {
      if (elmnt != x[i] && elmnt != inp) {
        x[i].parentNode.removeChild(x[i]);
      }
    }
  }
  /*execute a function when someone clicks in the document:*/
  document.addEventListener("click", function (e) {
      closeAllLists(e.target);
      });
}

/*An array containing all the country names in the world:*/
var parishes = ['Allinge','Bornholms Baptistkirke','Bodilsker','Christiansø','Hasle','Ibsker','Katolsk kirke','Klemensker','Knudsker','Neksø','Neksø - Methodist','Nyker','Nylarsker','Olsker','Pedersker','Povlsker','Rutsker','Rø','Rønne','Rønne og Allinge - Methodist','Sandvig','Svaneke','Vester Marie','Åker','Åkirkeby','Øster Larsker','Øster Marie','Alsønderup','Annisse','Asminderød','Birkerød','Bistrup','Blistrup ','Blovstrød','Dråby','Egebæksvang','Esbønderup','Farum','Ferslev','Frederiksborg Slotssogn','Frederikssund','Frederikssund og Ude Sundby','Frederiksværk','Ganløse','Gerlev','Gilleleje','Græse','Græsted','Grønholt','Gørløse','Hellebæk','Helsinge','Helsingør','Hillerød','Hornbæk','Humlebæk','Hørsholm','Jørlunde','Karlebo','Kregme','Krogstrup','Kyndby','Lille Lyngby','Lillerød','Lynge','Melby','Mårum','Nødebo','Nørre Herlev','Oppe Sundby','Præstevang','Ramløse','Selsø','Sigerlevvester','Skibby','Skuldelev','Skævinge','Slagslunde','Slangerup','Snostrup','Stenløse','Strø','Søborg','Tibirke','Tikøb','Tjæreby','Torup','Uggeløse','Usserød','Uvelse','Valby','Vejby','Veksø','Vellerup','Vinderød','Ølsted','Ølstykke','Agerskov','Aller','Bevtoft','Bjerning','Branderup','Christiansfeld',' Tyrstrup','Fjelstrup','Fole','Frørup','Gram','Grarup','Haderslev (Gammel Haderslev)','Haderslev - Vor Frue','Halk','Hammelev','Hjerndrup','Hjerting','Hoptrup','Hygum','Jegerup','Jels','Lintrup','Maugstrup','Moltrup','Nustrup','Oksenvad','Rødding','Skodborg','Skrave','Skrydstrup','Sommersted','Stepping','Sønder Starup','Tirslund','Toftlund','Vedsted','Vilstrup','Vojens','Vonsbæk','Åstrup','Øsby','Øster Lindet','Abildgård',];

/*initiate the autocomplete function on the "search" element, and pass along the parishes array as possible autocomplete values:*/
autocomplete(document.getElementById("search"), parishes);
</script>

Open in new window

0
Julian HansenCommented:
I have tried your model. It is not working at all.
Can't comment without code. I repeated the exercise here and it works fine. You can see it working here
Did you remember to enclose your input in the autocomplete class
<div class="autocomplete">
  <input id="search" type="text" name="sogn" placeholder="Søg pr. sogn">
</div>

Open in new window

Give that a go and see if it works. If not then I would recommend you go with one of the libraries I posted above. They are tried and tested and use all over the net.
0
Peter KromanSales ExecutiveAuthor Commented:
Thansk Julian,

I will try that out again:)
0
Peter KromanSales ExecutiveAuthor Commented:
I have got the autocomplete working with this form:
<form autocomplete="off" action="">
                        <div class="autocomplete" style="width:300px;">
                          <input id="search" type="text" name="sogn" placeholder="Søg pr. sogn">
                        </div>
                        <input type="submit" value="Søg">
                        <input type="reset" value="Nulstil">
                      
                      </form>

Open in new window


But I wonder if it is possible to create the array within the script in another file and call it in stead. The fact is that I need to use this autocomplete in quite a number of pages, and it would make the following maintenance very much easier if I only needed to maintain this array once.

The array (this is only a little part of it - when finished it will hold appr. 2200 names):
/*An array containing all the country names in the world:*/
var parishes = ['Allinge','Bornholms Baptistkirke','Bodilsker','Christiansø','Hasle','Ibsker','Katolsk kirke','Klemensker','Knudsker','Neksø','Neksø - Methodist','Nyker','Nylarsker','Olsker','Pedersker','Povlsker','Rutsker','Rø','Rønne','Rønne og Allinge - Methodist','Sandvig','Svaneke','Vester Marie','Åker','Åkirkeby','Øster Larsker','Øster Marie','Alsønderup','Annisse','Asminderød','Birkerød','Bistrup','Blistrup ','Blovstrød','Dråby','Egebæksvang','Esbønderup','Farum','Ferslev','Frederiksborg Slotssogn','Frederikssund','Frederikssund og Ude Sundby','Frederiksværk','Ganløse','Gerlev','Gilleleje','Græse','Græsted','Grønholt','Gørløse','Hellebæk','Helsinge','Helsingør','Hillerød','Hornbæk','Humlebæk','Hørsholm','Jørlunde','Karlebo','Kregme','Krogstrup','Kyndby','Lille Lyngby','Lillerød','Lynge','Melby','Mårum','Nødebo','Nørre Herlev','Oppe Sundby','Præstevang','Ramløse','Selsø','Sigerlevvester','Skibby','Skuldelev','Skævinge','Slagslunde','Slangerup','Snostrup','Stenløse','Strø','Søborg','Tibirke','Tikøb','Tjæreby','Torup','Uggeløse','Usserød','Uvelse','Valby','Vejby','Veksø','Vellerup','Vinderød','Ølsted','Ølstykke','Agerskov','Aller','Bevtoft','Bjerning','Branderup','Christiansfeld',' Tyrstrup','Fjelstrup','Fole','Frørup','Gram','Grarup','Haderslev (Gammel Haderslev)','Haderslev - Vor Frue','Halk','Hammelev','Hjerndrup','Hjerting','Hoptrup','Hygum','Jegerup','Jels','Lintrup','Maugstrup','Moltrup','Nustrup','Oksenvad','Rødding','Skodborg','Skrave','Skrydstrup','Sommersted','Stepping','Sønder Starup','Tirslund','Toftlund','Vedsted','Vilstrup','Vojens','Vonsbæk','Åstrup','Øsby','Øster Lindet','Abildgård',];

Open in new window

0
Peter KromanSales ExecutiveAuthor Commented:
In fact I have alle these names of parishes in an database table called Kirkebogssogne and a column named Sogn.
Could I perhaps draw them from there in stead of typing them directly into the script??
0
Julian HansenCommented:
Yes you can - but I would definitely recommend one of the above libraries if you are going to do that - as they have support for that built in.
0
Peter KromanSales ExecutiveAuthor Commented:
Yes that sounds appealing, but this searchform has a lot of integration to the rest of the page, and I am not skilled enough to make that work with the library (have looked into the  jQueryUI Autocomplete library).

What the searchform does is to search 4 dfferent database tables and present results for the parish searched for in three columns on the page. Try to search for  "Allinge" in the searchfield, and you will see three columns of information about the parish Allinge.
0
Julian HansenCommented:
Are we getting distracted? The question is about how to get the list of parish names from the server based on a partial input in the search bar? What happens after you search should not be relevant?

From the jQueryUI Autocomplete Remote Source sample
    $( "#birds" ).autocomplete({
      source: "search.php",
      minLength: 2,
      select: function( event, ui ) {
        log( "Selected: " + ui.item.value + " aka " + ui.item.id );
      }
    });
  } );

Open in new window

As you can see from the above you bind the autocomplete to your search input, you provide a PHP script to supply the values.

In search.php you need to get the term
<?php
$host = 'localhost';
$user = 'username';
$pass = 'password';
$db = 'database;

$term = isset($_GET['term']) ? $_GET['term']: '';

$conn = new mysqli($host, user, $pass, $db);

if (!$conn) {
  // handle db connect error here
}

$query = "SELECT * FROM `parishes` WHERE `parishname` like '%{$term}%'";
$result = mysqli_query($conn, $query);

$results = array();
while($row = mysqli_fetch_object($result)) {
   $item = new stdClass;
   $item->id = $row->agent_id;
   $item->label = $row->name;
   $item->value = $row->name;
   $results[] = $item;
}
die(json_encode($results));

Open in new window

0
Peter KromanSales ExecutiveAuthor Commented:
Thanks Julian,

I will work on that :)
0
Peter KromanSales ExecutiveAuthor Commented:
Now I am a little further :)

With this script(s):
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
        <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
        <script>
        $( function() {
          function log( message ) {
            $( "<div>" ).text( message ).prependTo( "#log" );
            $( "#log" ).scrollTop( 0 );
          }
       
          $( "#search" ).autocomplete({
            source: "search.php",
            minLength: 2,
            select: function( event, ui ) {
              log( "Selected: " + ui.item.value + " aka " + ui.item.id );
            }
          });
        } );
        </script>

Open in new window


This html:
<form autocomplete="off" action="" style="display: flex;">
                  <div class="ui-widget">
                    <input id="search" name="sogn" placeholder="Søg pr. sogn" style="margin-right: 15px;">
                  </div>
                   
                  <div class="ui-widget" style="font-family:Arial">

                     <input type="submit" value="Søg">
                    <input type="reset" value="Nulstil">
                      
                    </form>

Open in new window


And this search.php:
<?php
$host = 'mysql31.unoeuro.com';
$user = 'genealogisk_dk1';
$pass = 'my Password';
$db = 'genealogiskforum_dk_db9';

$term = isset($_GET['term']) ? $_GET['term']: '';

$conn = new mysqli($host, $user, $pass, $db);

if (!$conn) {
  // handle db connect error here
}

$query = "SELECT Sogn FROM kirkebogssogne WHERE Sogn like '%{$term}%'";
$result = mysqli_query($conn, $query);

$results = array();
while($row = mysqli_fetch_object($result)) {
   $item = new stdClass;
   $item->id = $row->agent_id;
   $item->label = $row->name;
   $item->value = $row->name;
   $results[] = $item;
}
die(json_encode($results));

Open in new window


I get an autocomplete result: But the result is a long list of 'null' on a black background. It seems like it is finding what it is supposed to find in the autocomplete but is displays only null's.  Furthermore when clicking a null in the list nothing happens - at this stage I need the clicked value to appear in the searchfield - or even better that submit is activated when clicking in the autocomplete list.

As the last thing the new inputfeld seems to be pushing the rest of my page (below the inputfield) to the right which it should not do, but just appear on top of the other content on the page (example: https://kroweb.dk/gfdev/arkivalier/sognefakta/?sogn=Bellinge).

If you can help me fix these things I believe this is the solution I will go with :)
0
Julian HansenCommented:
Except you need to change this
while($row = mysqli_fetch_object($result)) {
   $item = new stdClass;
   $item->id = $row->agent_id;
   $item->label = $row->name;
   $item->value = $row->name;
   $results[] = $item;
}

Open in new window

I don't have view on your database so I don't know what your fields are you need to change the agent_id, name fields to match your database.
0
Peter KromanSales ExecutiveAuthor Commented:
When doing like this (I don't use the label value) nothing happens. It does not show the null's anymore - it is showing nothing :)

while($row = mysqli_fetch_object($result)) {
   $item = new stdClass;
   $item->id = $row->id;
   //$item->label = $row->name;
   $item->value = $row->Sogn;
   $results[] = $item;

Open in new window


The structure of my database table is this:
Sk-rmbillede-2018-05-16-08.25.08.png
0
Julian HansenCommented:
why is $item->label commented out?
It should be like this
while($row = mysqli_fetch_object($result)) {
   $item = new stdClass;
   $item->id = $row->id;
   $item->label = $row->Sogn;
   $item->value = $row->Sogn;
   $results[] = $item;
}

Open in new window

0
Peter KromanSales ExecutiveAuthor Commented:
When I do like this:
while($row = mysqli_fetch_object($result)) {
   $item = new stdClass;
   $item->id = $row->id;
   $item->label = $row->Sogn;
   $item->value = $row->Sogn;
   $results[] = $item;
}

Open in new window

I get nothing

When I do like this:
while($row = mysqli_fetch_object($result)) {
   $item = new stdClass;
   $item->id = $row->id;
   $item->label = $row->sogn;
   $item->value = $row->sogn;
   $results[] = $item;
}

Open in new window


I get a long list of null's
0
Peter KromanSales ExecutiveAuthor Commented:
I can see it is working. I made the autoload background blue, and I can see that it is trying to fetch something, But nothing is autocompleted.

I give you the code fragments again:
Script:
<script>
        $( function() {
          function log( message ) {
            $( "<div>" ).text( message ).prependTo( "#log" );
            $( "#log" ).scrollTop( 0 );
          }
       
          $( "#search" ).autocomplete({
            source: "search.php",
            minLength: 2,
            select: function( event, ui ) {
              log( "Selected: " + ui.item.value + ui.item.id );
            }
          });
        } );
        </script>

Open in new window


HTML form:
                  <form autocomplete="off" action="" style="display: inline-block">
                    <div class="ui-widget">
                      <input id="search" name="sogn" placeholder="Søg pr. sogn" style="margin-right: 15px;">
                      <input type="submit" value="Søg">
                      <input type="reset" value="Nulstil">
                    </div>
                   
                  <div class="ui-widget" style="font-family:Arial"></div>
                      
                  </form>

Open in new window


search.php:
<?php
$host = 'mysql31.unoeuro.com';
$user = myCredentials';
$pass = 'myCredentials';
$db = 'genealogiskforum_dk_db9';

$term = isset($_GET['term']) ? $_GET['term']: '';

$mysqli = new mysqli($host, $user, $pass, $db);

if (!$mysqli) {
  // handle db connect error here
}

//include_once('kb_data_connection.php')

$query = "SELECT * FROM sogne WHERE Sogn like '%{$term}%'";
$result = mysqli_query($mysqli, $query);

$results = array();
while($row = mysqli_fetch_object($result)) {
   $item = new stdClass;
   $item->id = $row->id;
   $item->label = $row->Sogn;
   $item->value = $row->Sogn;
   $results[] = $item;
}
die(json_encode($results));

Open in new window


Database table structure:
Sk-rmbillede-2018-05-16-12.03.13.png
0
Julian HansenCommented:
What do you get if you call search.php directly with a term
For example

http://yourserver/path/search.php?term=Ka

Open in new window

Please replace the server and path so it matches the path to your Search.php file
Please replace the term with something that is going to match your database.
Post what that returns.

EDIT
Just to be clear - I am asking for you to enter the URL above into your browser and show us what results you get
0
Peter KromanSales ExecutiveAuthor Commented:
Honestly I don't know what I did or what happened.
But now it seems to be working nicely :)

The only little thing I need to fix is that the autocompletion list is with black background and white text, but I believe that I can adjust that in CSS ??
0
Peter KromanSales ExecutiveAuthor Commented:
But how do I adres that in CSS??
0
Julian HansenCommented:
In this file
https://kroweb.dk/gfdev/templates/template_style.css
On line 6
You have this
ul {
	margin: 0;
	padding: 0;
	list-style: none;
	color: #fff !important; /* <= REMOVE THIS */
	background-color: #fff; /* CHANGE THIS */
}

Open in new window

0
Peter KromanSales ExecutiveAuthor Commented:
I cant do that. This is adressing the top menu bar which I don't want to change.
0
Julian HansenCommented:
Your problem is you are styling the <ul> tag directly - that means you will style all <ul> tags on the page. Unless that is your intention always target your elements with a class or id to isolate them from other tags of the same type.

In your case you can do one of these
#my_main_nav {
...
}

Open in new window

Or
ul.main-nav {
...
}

Open in new window

0
Peter KromanSales ExecutiveAuthor Commented:
OK. But I can not adres the ul that the autocomplete generates directly in CSS?
0
Julian HansenCommented:
You can - the <ul> on the drop down has many classes you can address

ul.ui-autocomplete

However, the default styling will apply as soon as you style the ul that is governing them menu properly as per my post above.
0
Peter KromanSales ExecutiveAuthor Commented:
Yes - but I might be interested in styling the ul a little different from the default style :)

The ul.ui-autocomplete in not working in CSS.
0
Julian HansenCommented:
Peter,

You need to follow my directions.

You cannot have this style
ul {
	margin: 0;
	padding: 0;
	list-style: none;
	color: #fff !important;
	background-color: #000 !important;
}

Open in new window

You need to target your menu
ul#my_main_nav {
	margin: 0;
	padding: 0;
	list-style: none;
	color: #fff !important;
	background-color: #000 !important;
}

Open in new window

Once you do that you will be able to style
ul.ui-autocomplete
If you don't then that style is going to override what you are trying to do.

Please make that change.
0
Peter KromanSales ExecutiveAuthor Commented:
I understand.

But this change has many implications for me, so I will work on it easy and quiet, and get back when ever I am ready.
0
Julian HansenCommented:
I understand.

I would not recommend it but you can always do this
ul.ui-autocomplete {
  background-color: blue!important;
  color: white!important;
}

Open in new window

I don't like using important - but if the alternative is not going to work for you - you can do it this way.
0
Peter KromanSales ExecutiveAuthor Commented:
Thanks Julian,

I have got everything working now.

One last question is if it is possible to execute a submit when clicking a result in the dropdown list. That way I could skip the submit button and my users would get quicker to their result :)
0
Julian HansenCommented:
Yes you can
 $( "#search" ).autocomplete({
            source: "../../collecting_page2/autocomplete/search.php",
            minLength: 2,
            select: function( event, ui ) {
              log( "Selected: " + ui.item.value + ui.item.id );
// DO YOUR SUBMIT HERE
            }
          });

Open in new window

Except you are doing something weird on the page - you have two forms - which is the one that you want to submit
0
Peter KromanSales ExecutiveAuthor Commented:
Thanks Julian for very good advices and guidance :)
0
Julian HansenCommented:
You are welcome.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
HTML

From novice to tech pro — start learning today.