1

I have tried few things bet they don't seem to work, my code works fine if I populate the array myself without database therefore the problem is with retrieving data from database.

var countries = <?php
require('connection.php');
$query = 'SELECT product_name FROM products';
$result = mysqli_query($conn, $query);
while($products = mysqli_fetch_array($result, MYSQLI_NUM)){
    echo json_encode($products);
//OR
//$products = mysqli_fetch_all($result, MYSQLI_NUM);
//echo json_encode($products);
}
 ?>;

This is the code I have tried but it is not working I am sending countries to a function

autocomplete(document.getElementById("myInput"), countries);

In this function I am parsing through the array in such a way

for (i = 0; i < arr.length; i++) {
    /*check if the item starts with the same letters as the text field value:*/
    /*here arr is the array 'countries' send to the function autocomplete*/
    if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {//code snippet
   }}

1 Answer 1

1

You are echoing a JSON string at each iteration of the while() loop. So, it will writes a non-valid JSON string. You could create an array, populate it, and finally, write it as JSON:

<?php
require('connection.php');
$query = 'SELECT product_name FROM products';
$result = mysqli_query($conn, $query);
$products = []; // new array
while($product = mysqli_fetch_array($result, MYSQLI_NUM)) {
    $products[] = $product ; // push into array
}
// finally, write JSON:
?>
var countries = <?php echo json_encode($products) ?>;
Sign up to request clarification or add additional context in comments.

7 Comments

I have already tried this too because this solution was given in the answer of an another question at stackoverflow. Is there any other way of doing this?
@Anonymous Please, what's the problem you're facing with this? What is the given error? Could you please show the output? Thanks.
I am trying to send an array to a function which will parse through the array and apply autocomplete to the textfield. I have now realized that I have been parsing the array as an numeric array but maybe I am getting an associative array in "countries" I am updating the Question, maybe that will help in understanding what I am trying to achieve
@Anonymous Ok, I see. Could you please add a little part of your array? Thank you.
var countries = ["Santana Gamma - Syrah","Santana Axel - Black","Canon EOS 5D Mark IV","Sony Alpha99 II","Nikon D3300","Pentax K-1","microSD Card","Canon EOS 77D"]; //this is the kind of array I am trying to get from the database and if I explicitly define it then the code is working fine
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.