0

I'm stuck trying to populate a search datalist with the titles stored in mySQL using jquery .post ajax method. Problem is that can't get it to load the titles. Here is my code:

index.php

//// of couse jquery cdn link is included at header.php  ////

<script>
$(document).ready(function(){
   $('#datalistOptions').keyup(function(){
      $.post('search_title.php',{
         title:this.value,
         load:5
      }, function(data){
         $('#datalistOptions').html(data);
      });
   });
});
</script>

<datalist id="datalistOptions">
</datalist>

search_title.php

<?php
include_once('config.php');

$title = $_POST['title'];
$load = $_POST['load'];

$sql = "SELECT (`movie_id`,`title`) FROM `movies` WHERE `title` LIKE '$title%' ORDER BY `title` ASC LIMIT $load";
$result = mysqli_query($conn, $sql);
$titles = mysqli_fetch_all($result, MYSQLI_ASSOC);
mysqli_free_result($result);

foreach ($titles as $title) :
?>
   <option data-value=".<?php echo $title['movie_id']; ?>" value="<?php echo $title['title']; ?>"></option>
<?php endforeach; ?>

######### PLEASE NOTE!! ################ I will fix the PREPARED STATEMENTS later, first I'm trying to get the AJAX to work, so pls don't mind the simple querys for the moment.

xelfury
  • 203
  • 2
  • 9
  • 1
    you are aware that this is bound to the keyup event when the datalist has focus right? So the ajax call will not be made untill a keypress (on the way up) has occurred. Has the request to the server been sent, did you check chrome debug tools to check if the POST was made, also one observation is that you are using a POST request to obtain a list of data, thats not really restful. I know that sometimes its easier to post an object than translate the object into URL params, however do you want the users to be able to book mark the site etc... – Max Carroll Jul 06 '20 at 00:03
  • yes im aware that is bounded to the keyup, which at that moment i want to sent the request to search.php and look for the first 5 titles on my database and return an `` tag that will be inserted into the `` tag to get the titles as options. Problem is i cant get jquery to insert the callback into it. – xelfury Jul 06 '20 at 00:09
  • Have you verified jquery is there sometimes the $ may not be jquery just double check that. Do you have an errors in the javascript console. Try and get an `alert("Fired!")` or `console.log("FIRED!")` function to fire before your ajax, so then you know straight a way if its worked, then replace with the ajax call. If that doesnt work do `var x = $('#datalistOptions'); console .log(x) ` to see what the jquery element obtained is when its executed to ensure you have the right element. Hopefully one of these will help – Max Carroll Jul 06 '20 at 00:17
  • Im not getting anything to the console. it works great on an `` tag. Do you know how to select with jquery the value in a datalist tag? – xelfury Jul 06 '20 at 00:23
  • 1
    Oh right if its working on an input but not a datalist, perhaps try a different event like onChange or something? – Max Carroll Jul 06 '20 at 00:27
  • Nop, not working either. I'm pretty sure this has something to do with selecting the value at the inner HTML inside the datalist tag – xelfury Jul 06 '20 at 00:35
  • inspect the DOM using debug tools afterwards to see how it has been manipulated for a clue – Max Carroll Jul 06 '20 at 07:14
  • @MaxCarroll I was able to get it working with the code in the answer below. Though doesn't look very nice because at the end does something weird like reloads twice or something. I've decided to use use a div instead. – xelfury Jul 06 '20 at 12:33

1 Answers1

0

I was able to get it to work with the ajax() method.

<script>
   $(document).ready(function() {
      $("#search").on("input", function() {
         var options = {};
         options.url = "search_title.php";
         options.type = "POST";
         options.data = {
            "title": $("#search").val(),
            "load": 5
         };
         options.dataType = "json";
         options.success = function(data) {
            $("#searchOptions").empty();
            for (var i = 0; i < data.length; i++) {
               $("#searchOptions").append("<option data-value=\"."+ data[i].id +"\" value='" + data[i].title + "'></option>");
            }
         };
         $.ajax(options);
      });
   });
</script>

html

<input id="search" list="searchOptions" class="form-control mb-3 filters-datalist" placeholder="Type to search...">
<datalist id="searchOptions"></datalist>
xelfury
  • 203
  • 2
  • 9
  • You should take a look at a concept called denouncing (a small duration of pause inbetween service calls because you don't want a service call every time the input changes, this is because it could be fired on every keypress etc... ), since it looks like your using vanilla JS with Jquery, you can either write your own functions to debounce this or use a library like underscore to do it for you https://stackoverflow.com/questions/23493726/how-to-properly-debounce-ajax-requests https://levelup.gitconnected.com/debounce-in-javascript-improve-your-applications-performance-5b01855e086 – Max Carroll Jul 07 '20 at 09:12
  • Also is this for a WordPress plugin or theme? If not and you have some choice about the app technologies then it might be an idea to use a framework such as React, Vue or Angular. Although they have an initial learning curve to begin with its a fantastic way to decouple the presentation from the logic, with this approach your presentation is tangled up in the logic of fetching the data itself. If you have to modify what that looks like or the shape of the data changes, because things aren't separated nicely its going t o be hard work to maintain – Max Carroll Jul 07 '20 at 09:24
  • However if this is for WordPress I understand – Max Carroll Jul 07 '20 at 09:27
  • @MaxCarroll This is not for WordPress. It is just for a personal project. The code works but the javascript or tag (I don't know what is doing it) sort of does double request every time the keyboard is pressed so it looks funky and does not look like it should.I will look into your recommendation for denouncing. – xelfury Jul 07 '20 at 13:47
  • Sorry I actually meant `debouncing` small typo there (it won't let me edit the comment now). Also not sure exactly how the `input` onchange event works, but try exploring others to see if you get the same result. https://api.jquery.com/category/events/ there's a list of all the events you can use. Try and use experimentation to determine whether the service call is firing twice due to the nature of the event type used to fire, or whether something in your code is causing that event to fire twice. Bind that function to a button instead just to test and determine this – Max Carroll Jul 08 '20 at 10:24