-1

I'm trying to find a solution to put in bold the string of characters that is being searched in the suggestions of a searchbar having a JQuery autocomplete function, as in this picture : styled autocomplete list Here are the relevant parts of my files : https://jsfiddle.net/07getk4z/ HTML :

<html><head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script>
$(function(){
$(\"#suggFRbis\").autocomplete({
source: \"sugg.php\",
autoFocus: false,
select: function(event, ui) {
$(\"#sugg\").val(ui.item.label);
$(\"#formid\").submit(); }
});
});
</script>
</head><body>
<form id="formid" action="file.php" method="post">
<p>Enter text</p>
<input id="sugg" type="text" name="forme" class="barre" onkeyup="autocomplet()">
</form></body></html>

JS/Jquery :

 <?php
$dbHost = 'localhost';
$dbUsername = 'username';
$dbPassword = 'password';
$dbName = 'dbname';
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
$searchTerm = utf8_decode($_GET['term']);
$query = $db->query("SELECT * FROM table WHERE column LIKE '%".$searchTerm."%' LIMIT 10");
$sugg = array();
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
$data['value'] = $row['column'];
array_push($sugg, utf8_encode($data['value']));
}
}
echo json_encode($sugg);
?>

I'm a complete beginner so I hope I will understand your solutions^^ I'll do my best :D Many thanks in advance!

bobo
  • 1
  • 1
    **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman May 12 '21 at 10:26

1 Answers1

0

Consider the following example.

$(function() {
  var availableTags = [
    "ActionScript",
    "AppleScript",
    "Asp",
    "BASIC",
    "C",
    "C++",
    "Clojure",
    "COBOL",
    "ColdFusion",
    "Erlang",
    "Fortran",
    "Groovy",
    "Haskell",
    "Java",
    "JavaScript",
    "Lisp",
    "Perl",
    "PHP",
    "Python",
    "Ruby",
    "Scala",
    "Scheme"
  ];

  function makeBold(needle, haystack) {
    return haystack.replace(new RegExp("(" + needle + ")", "i"), "<b class='bold'>$1</b>");
  }

  $("#sugg").autocomplete({
    source: availableTags,
    autoFocus: false,
    select: function(event, ui) {
      //$("#formid").submit();
    }
  }).autocomplete("instance")._renderItem = function(ul, item) {
    return $("<li>")
      .append("<div>" + makeBold($("#sugg").val(), item.label) + "</div>")
      .appendTo(ul);
  };
});
.bold {
  font-weight: bold;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<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>

<form id="formid" action="file.php" method="post">
  <p>Enter text</p>
  <input id="sugg" type="text" name="forme" class="barre" />
</form>

This uses .substr() to split the resulting word(s) based on the length the User has entered. So for example, if they enter "cold" the resulting HTML will be <li><div><span class='bold'>Cold</span>fusion</div></li>.

This is based on the following Demo: https://jqueryui.com/autocomplete/#custom-data

In regards to your PHP, you are vulnerable to SQL Injection. Please read: https://www.php.net/manual/en/security.database.sql-injection.php

Update

I updated the code to use .replace().

halfer
  • 19,824
  • 17
  • 99
  • 186
Twisty
  • 30,304
  • 2
  • 26
  • 45
  • Thank you. It works if I replace the span with . It may be due to ill-formed css instructions (?) However the styled characters do not correspond exactly to the typed characters : they correspond to the first 3 characters of the suggestion if I type 3 characters (present elsewhere in the string of characters, not necessarily in the beginning). I'd like to style only the typed characters present anywhere in the suggested strings of characters. – bobo May 12 '21 at 18:33
  • @bobo good point. Then will need to use a Regular Expression to find the term in the string text and replace it with the wrapped text. Will see if I can update my answer. – Twisty May 12 '21 at 18:36
  • @bobo I have updated the answer with a `haystack.replace(new RegExp("(" + needle + ")", "i"), "$1");` that will wrap it in the position of the word. – Twisty May 12 '21 at 19:00
  • Sorry I can't make the update work. I'll keep searching. Thank you anyway for your work. – bobo May 12 '21 at 19:11
  • @bobo there is more to the update in the code snippet. – Twisty May 12 '21 at 21:39
  • Actually your code works well, of course, as we can see with the code snippet, and I make it work too with this exact code (with the example data "availableTags")... so I realized that when I replaced the source "availableTags" with my PHP file (which uses my SQL database), I also removed "$(function() { });" (the very beginning and very end of your code, wrapping the whole). Apparently this is necessary (as you can see I'm a beginner^^). Thanks a lot for your efficient solution! – bobo May 12 '21 at 22:37
  • It works if we don't forget to put accents on characters (for example, the search "cafe" isn't bold because the suggestion has an accent : café). If someone can help me that would be great, otherwise I'm already glad that the problem is practically resolved. – bobo May 13 '21 at 21:07
  • Hi Twisty. Please refrain from adding "hope this helps" and other social niceties. A succinct and technical style of writing is preferred ([see here](https://stackoverflow.com/posts/57927587/revisions)). – halfer May 14 '21 at 07:44