0

autocomplete-api.php

<?php
    session_start();
    error_reporting(0);
    include("includes/config.php");

    $data = array();
    $query = "SELECT product_name FROM inventory group by product_name;";
    $query .= "SELECT name FROM brands;";
    $query .= "SELECT name FROM categories;";

    mysqli_multi_query($con,$query);
    $result = mysqli_store_result($con);

    while($row = mysqli_fetch_assoc($result)) 
    {
        $data[] = array(
                        'products' => $row['product_name']
                    );
    }

    mysqli_free_result($result);
    mysqli_next_result($con);

    $result = mysqli_store_result($con);

    while ($row = mysqli_fetch_assoc($result)) {
        $data[] = array(
                        'products' => $row['name']
                    );
    } 

    mysqli_free_result($result);
    mysqli_next_result($con);

    $result = mysqli_store_result($con);

    while ($row = mysqli_fetch_assoc($result)) {
        $data[] = array(
                        'products' => $row['name']
                    );
    } 

    mysqli_free_result($result);
    mysqli_close($con);

    $results = json_encode($data);
    print($results);
?>

autocomplete.js

function autocomplete(inp, arr) {
  var currentFocus;
  inp.addEventListener("input", function(e) {
      var a, b, i, val = this.value;
      closeAllLists();
      if (!val) { return false;}
      currentFocus = -1;
      a = document.createElement("DIV");
      a.setAttribute("id", this.id + "autocomplete-list");
      a.setAttribute("class", "autocomplete-items");
      this.parentNode.appendChild(a);
      for (i = 0; i < arr.length; i++) {
        if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
          b = document.createElement("DIV");
          b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
          b.innerHTML += arr[i].substr(val.length);
          b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
          b.addEventListener("click", function(e) {
              inp.value = this.getElementsByTagName("input")[0].value;
              closeAllLists();
          });
          a.appendChild(b);
        }
      }
  });
  inp.addEventListener("keydown", function(e) {
      var x = document.getElementById(this.id + "autocomplete-list");
      if (x) x = x.getElementsByTagName("div");
      if (e.keyCode == 40) {
        currentFocus++;
        addActive(x);
      } else if (e.keyCode == 38) {
        currentFocus--;
        addActive(x);
      } else if (e.keyCode == 13) {
        e.preventDefault();
        if (currentFocus > -1) {
          if (x) x[currentFocus].click();
        }
      }
  });
  function addActive(x) {
    if (!x) return false;
    removeActive(x);
    if (currentFocus >= x.length) currentFocus = 0;
    if (currentFocus < 0) currentFocus = (x.length - 1);
    x[currentFocus].classList.add("autocomplete-active");
  }
  function removeActive(x) {
    for (var i = 0; i < x.length; i++) {
      x[i].classList.remove("autocomplete-active");
    }
  }
  function closeAllLists(elmnt) {
    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]);
      }
    }
  }
  document.addEventListener("click", function (e) {
      closeAllLists(e.target);
      });
}
$.ajax({
    type:"GET",
    url:"http://localhost/leafteaculture/autocomplete-api.php",
    datatype:"JSON",
    success:function(json){
        alert(json);
        /*$.each(json, function(key, item) {
            var countries =  item.products;
            alert(countries);
        });*/
    }
});

Index.php

<input type="text" name="pro_duct" id="pro_duct" />

<script src="<?php echo $base_url; ?>assets/js/autocomplete.js"></script>
<script>
    autocomplete(document.getElementById("pro_duct"), countries);
</script>

Possible might be duplicate question. I have created autocomplete suggestion box where I have autocomplete-api.php where I have used json_encode function which is working fine but problem with autocomplete.js file. I am unable to get data from autocomplete-api.php file. I want to fetch data from autocompelete-api.php url and put it into the jquery variable. So, How can I do this? Please help me.

Thank You

omkara
  • 974
  • 5
  • 24
  • 50
  • I've never used `print` when sending JSON data from PHP to an AJAX call. I've always used `echo`. In the several examples I've googled, I don't find one that uses `print`. The two are supposed to be pretty much the same (`print` returns a value and only allows one argument; `echo` doesn't return a value and uses multiple arguments, and they both call the same function under the hood), but you might try using `echo` instead of `print` the way everyone else does. – BobRodes Aug 30 '18 at 06:44
  • Here is some more concise syntax for your multi query: https://stackoverflow.com/a/22469722/2943403 Better still, you should write a single query with two `UNION`s and alias the the first column of the first query `products`. – mickmackusa Aug 30 '18 at 14:43
  • Edit: nope, I've tested it, and print works the same as echo. Since you don't need the value that print returns, maybe that's why everyone uses echo. – BobRodes Aug 30 '18 at 19:23

2 Answers2

0

The possible problem might be that since you've used json_encode which returns a string and in the AJAX request you've specified the dataType to be JSON, AJAX is unable to find the required dataType in the response. You could simply remove the dataType property from the AJAX request. Once the data is fetched, you need to use JSON.parse to convert the string to JSON format.

Refer to AJAX documentation and json_encode for more info.

Hope this helps.

0

I think the first thing to fix is your php file -- let's boil that thing down. You can maintain the same query logic / resulset with much less hassle by using UNION keywords to form a single / more efficient query.

session_start();
header('Content-type: application/json');
include("includes/config.php");

if (!$result = $con->query("(SELECT product_name AS products FROM inventory GROUP BY product_name) UNION (SELECT name FROM brands) UNION (SELECT name FROM categories)")) {
    echo [];  // check $con->error; because your query failed
} else {
    echo json_encode($result->fetch_all(MYSQLI_ASSOC));
}

Yes, it really can be reduced THAT much! Here's proof that the query works.

From the same data, here is the generated json string:

[{"products":"One"},{"products":"Three"},{"products":"Two"},{"products":"Four"},{"products":"Five"},{"products":"Six"},{"products":"Seven"},{"products":"Eight"}]

Then, then the json string is received by your javascript, call var apiArray = = JSON.parse(json); so that you can work with the multi-dimensional array containing a single column of data.


...p.s. If you are worried about duplicate product names, you can weed out duplicates in the query:

SELECT DISTINCT product FROM (
    (SELECT product_name AS product FROM inventory GROUP BY product_name)
    UNION
    (SELECT name FROM brands)
    UNION
    (SELECT name FROM categories)
) Unionized
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
  • @omkara If this does not eliminate your issue. Please update your question to express what IS working as expected, what isn't, and any server-side and client-side errors. – mickmackusa Aug 30 '18 at 15:38