Autocomplete not working when array is filled from database - javascript

I used to use this kind of code before like 1 year ago and it worked.
Now I got a problem with the php code when I fill my array with elements from the database I can't do the autocomplete, but when I comment the part where I get the code form the database and uncomment //$elements = array("25qt", "45tr", "az12"); than the autocomplete works.
It looks like the array is filled correctly from the database cause when I open the php file alone and do a var_dump($elements); i get the content of the array accordingly. Any idea why its not working when i fill the array from the db but it works if I use an array like $elements = array("25qt", "45tr", "az12");.
HTML code:
<input id="tegjithepjeset" type="text" class="form-control">
jQuery code:
<script type="text/javascript">
$(document).ready(function(){
$("#tegjithepjeset").autocomplete({
source:'allParts.php',
minLength:1
});
});
</script>
Php code:
<?php
// An empty array:
$data = array();
// Create connection
include 'dbinfo.php';
$con=#mysqli_connect("$host","$user","$password","$db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$queryString = "SELECT code FROM ".$table;
$query =mysqli_query($con,$queryString);
$elements = array();
while($rowDB=mysqli_fetch_array($query)){
$elements[]="".$rowDB[0];
}
//var_dump($elements);
//$elements = array("25qt", "45tr", "az12");
//Loop through the array to find matches:
foreach ($elements as $elm) {
// Add matches to the $data array:
if (stripos($elm, $_GET['term']) !== false) $data[] = $elm;//here we fill our empty array with values
} // End of FOREACH.
// Return the data:
echo json_encode($data);
?>

Replace the $elements array code as shown below.
$elements = array();
while($rowDB=mysqli_fetch_array($query)){
// $elements[]="".$rowDB[0];
$elements[]=$rowDB[0];
}

Related

unable to get back end array data using JSON-encode

i have a script (Users.php) that uses JSON_encode to display an array of objects in an HTML table.
as in:
Users.php :
html //empty table
script //fills the table by using json encode to get php array and display the contents in the table
myPhp.php :
gets info from database and creates the array.
my php file is working just fine and so is my script. the only problem is when i use JSON_encode to get the array from php to the script it shows an error
:
Uncaught SyntaxError: Unexpected token '<' //on line 1 of php code
my Users.php:
<body >
<!-- adding user -->
<form class ="formArea" id = "addUser" action = "addUsers.php" method="POST">
<!-- addUsers.php will add users to the database then display Users.php again -->
</form>
<!-- display users -->
<table id="usersTable">
<!-- table to display user info -->
</table>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <!--jquery-->
<script>
//display all users in table
var users = <?php echo JSON_encode($rows); ?>
displayUsers(users);
function displayUsers(users){
for(i = 0; i<users.length; i++)
{
//create table row
//add user information to the row
}
}
</script>
</body>
my myPhp.php:
<?php
// fur UI Users.php
// calls all users from the db and displays them in users table
$sql = new mysqli("localhost","root","","atds");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
$query = "SELECT * FROM users";
$result = $sql->query($query);
while($row = $result->fetch_object())
{
$rows[]=$row;
}
// Close connection
$result->close();
$sql->close();
?>
what I've tried:
I tried including the php file before using json_encode
<?php include'myPhp.php' ?>
var users = <?php echo json_encode($rows); ?>
this works when i run Users.php but if i add a user (by submitting the form in this webpage), add user file reads Users.php again after the user is added, users will end up not displaying and i will have the same error:
Uncaught SyntaxError: Unexpected token '<'
//in line 1 of myPhp.php
is there any other way to use JSON_encode that won't result in this error?
I'm not getting the same error that you are but MyUsers.php does not know about the variable you are trying to use:
//display all users
//users array contains names and roles
var users = <br />
<b>Warning</b>: Undefined variable $rows in <b>/var/www/html/public/temp/myUsers.php</b> on line <b>17</b><br />
null
displayUsers(users);
function displayUsers(users){
for(i = 0; i<users.length; i++)
{
//create table row
//add user information to the row
}
}
There are a few different ways to get $rows in to myUsers.php.
One way that is easier to understand when you are learning is to do everything in one page: get your data at the top and render the HTML in the bottom.
MyUser2.php: I did not set up a database and hard coded the rows. Assuming that your database setup works you can removed the comments and the hard coded users. Note that since you are outputting a valid JSON array you do not have to re-parse it inside the javascript.
It will look like this in the browser:
//display all users
//users array contains names and roles
var users = ["user1","user2","user3"];
displayUsers(users);
function displayUsers(users){
for(i = 0; i<users.length; i++)
{
//create table row
//add user information to the row
document.write(users[i] + '<br>');
}
}
MyUser2.php file listing:
<?php
/*
// fur UI Users.php
// calls all users from the db and displays them in users table
$sql = new mysqli("localhost","root","","atds");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
$query = "SELECT * FROM users";
$result = $sql->query($query);
while($row = $result->fetch_object())
{
$rows[]=$row;
}
// Close connection
$result->close();
$sql->close();
*/
$rows[] = 'user1';
$rows[] = 'user2';
$rows[] = 'user3';
?>
<body >
<!-- adding user -->
<form class ="formArea" id = "addUser" action = "addUsers.php" method="POST">
<!-- addUsers.php will add users to the database then display Users.php again -->
</form>
<!-- display users -->
<table id="usersTable">
<!-- table to display user info -->
</table>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <!--jquery-->
<script>
//display all users
//users array contains names and roles
var users = <?php echo JSON_encode($rows); ?>;
displayUsers(users);
function displayUsers(users){
for(i = 0; i<users.length; i++)
{
//create table row
//add user information to the row
document.write(users[i] + '<br>');
}
}
</script>
</body>
This will get you started. A good framework for learning PHP is CodeIgniter. Laravel is a great framework and more popular but it adds a lot of magical stuff that makes regular PHP harder to learn.
In your "Users.php"
you should first include "myPhp.php"
<?php include'myPhp.php' ?>
and use it like this:
var json = '<?php echo JSON_encode($rows); ?>';
var users = JSON.parse(json);
solved.
the table was displaying correctly when i run Users.php but shows that error when adding a user by executing AddUsers.php which contains readfile('Users.php') at the end of it.
the problem was actually in readfile(Users.php)in addUsers.php.
readfile does not execute Users.php but only displays elements in it. therefore the JSON_encode never got executed and users weren't known to Users.php.
i solved this problem by changing readfile('Users.php') in addUsers to include 'Users.php';
Users.php code became :
<?php include 'displayUsers.php'; ?>;
var users = <?php echo JSON_encode($rows); ?>;
displayUsers(users);
function displayUsers(users){...}

PHP - When a checkbox gets checked send a request to run a query on the database

So I've been working on this code for awhile now and I've done a lot of debugging but can't figure this out. What I want to do is: if a checkbox is checked send a request to run a query on the mySQL database FROM items WHERE .class(of the checkbox) '<' this.value(of the checkbox again) then get the filtered results and then use my javascript to format it:
index.php:
<form>
<label><input type="checkbox" class="calories "name="calories" value="300">Less than 300</label><br>
<label><input type="checkbox" class="calories" name="calories" value="500">Less than 500</label><br>
</form>
<script>
$("input.calories:checkbox").on("change",function(){
if(this.checked){
var column = $(this).attr('class'); //The class determines which column of the table is called
var value = $(this).attr('value'); //Takes the numeric value from the selected box
console.log(column);
//$.post('showItems.php', {type: column});
//$.post('showItems.php', {value: value});
//Can we call the php code above to run a query using variables column and value?
//make a php function above and call it
// function below will run showItemss.php?c=column?v=value
$.ajax({
type: "POST",
url: "showItems.php" ,
data: { c: column,
v: value},
error: function(){console.log("error")},
success: function(data) {
console.log("success");
console.log(test);
console.log(filteredList);
</script>
Here is the PHP file showItems.php I'm calling (the relevant part):
//This array holds items from database.
$itemList = array();
//Connect and Select
$con = makeConnection($dbhost, $dbuser, $dbpass, $dbname);
//Get the value and type from the javascript below
//If the type is null display the whole table
$c = $_POST['c'];
//echo $c;
//$v = mysqli_real_escape_string($con,$v);
//$type = $_POST['value'];
if($c==null){
$query = "SELECT * FROM items";
}
else{
$v = $_POST['v'];
$query = "SELECT * FROM items WHERE ".$c."< ".$v."";
}
$result = mysqli_query($con, $query);
//Collect data from all items
while($row = $result->fetch_assoc())
{
$tempItem = new Item($row['itemID'], $row['itemName'], $row['price'], $row['description'], $row['calories'], $row['protein'], $row['choles'], $row['sodi'], $row['picLink']);
$itemList[] = $tempItem;
}
echo json_encode($query);
?>
<script>
var test = <?php echo json_encode($query); ?>;
var filteredList = <?php echo json_encode($itemList); ?>;
</script>
So I want this code to be run every time I click a checkbox in my Index.php file so I can get the updated filtered items, $itemList, but I cannot figure out how to do this. Something I've done to test this is store my php values as javascript variables, Include showItems.php then console.log the variables from ShowItems.php in Index.php, and the query isn't being updated upon click which makes sense I guess. In the AJAX success function 'data' contains the entire HTML source with an updated query, but I can't figure out how use only the specific code I need in the success function. Any ideas at all would be helpful.
Try doing this:
Go from on("change",...) to on("click",...)
Also try using instead of this.checked, $(this).prop("checked") which will return you true or false depending on wether the checkbox is checked or not.
You might want to change either your selector or your checkbox classes because both are the same, and can give you undesired functionality in order to get your values when you click on a checkbox, since the selector finds you both checkboxes.
Hope this ideas can get you closer where you want to be.
Cheers

mysqli select query to JS 2d array

I have seen some answers similar to this but they wont work for me.
I want to select data from a mysql database using mysqli / PHP and then pass the results to javascript.
I have the $conn stuff just above this, my code is at the very top of the file above the html, my script tags are in the body of the html. Is the correct place to have them? This just returns undefined, and if i try tweaking it i get unexpected < in index where i try and save it to the var ar. Or i can get unexpected ';' at the same line. Code shown below return unexpected ';'.
PHP
$query = "SELECT * FROM table";
$result = $conn->query($query);
while($row = $result->fetch_array())
{
$rows[] = $row;
}
$conn->close();
JavaScript
<script type="text/javascript">
var ar = <?php echo json_encode($rows)?>;
console.log(ar[0][0]);
</script>

array_push flat array issue - need to be able to add multiple variables to the array

I am trying to add a pair of variables 'product_name' and 'photos' (which is the URL of the car photo) into an array. I have a friend that said my efforts are failing because I am pushing into a flat array. I've looked to see how to do this with variable pairs and am stymied. He had suggested pushing row into $isotopecubes instead of how I have it below, but when I try I am getting null values. I need to be able to access val.photo and val.product_name in my javascript call in my php file that references this ajax code.
Note: if I just use:
array_push($isotopecubes, $row['photo']);
I get back the following JSON response on my console:
"/images/photos/cars/vw/14_Virginia_L.jpg",
"/images/photos/cars/mazda/2013/14hybrid.jpg"
so I know I am reaching the database and getting the correct values. Here is my ajax code:
<?php
include '../../global_config.php';
include 'config.php';
if ($_GET['action'] == 'get-images') {
$selectSql = "SELECT product_name, photo FROM cars WHERE publish = 1;";
$isotopecubeResult = $db->query($selectSql);
$isotopecubes = array();
while($isotopecubeResult->fetchInto($row, DB_FETCHMODE_ASSOC)) {
array_push($isotopecubes, $row['photo'], $col['product_name']);
// $isotopecubes = array_merge($isotopecubes, $row['photo']);
}
echo json_encode($isotopecubes);
}
?>
It can be done by
<?php
include '../../global_config.php';
include 'config.php';
if ($_GET['action'] == 'get-images') {
$selectSql = "SELECT product_name, photo FROM cars WHERE publish = 1;";
$isotopecubeResult = $db->query($selectSql);
$isotopecubes = array();
while($isotopecubeResult->fetchInto($row, DB_FETCHMODE_ASSOC)) {
//array_push($isotopecubes, $row['photo'], $col['product_name']);
// $isotopecubes = array_merge($isotopecubes, $row['photo']);
$isotopecubes[] = array('product_name' => $row['product_name'], 'photo' => $row['photo']);
}
echo json_encode($isotopecubes);
}
?>
Now you will be able to get value through val.product_name and val.photo

Inserting MySQL results from PHP into JavaScript Array

I'm trying to make a very simple autocomplete function on a private website using a trie in JavaScript. Problem is the examples I have seen and trying are just using a predefined list in a JavaScript array.
e.g. var arrayObjects = ["Dog","Cat","House","Mouse"];
What I want to do is retrieve MySQL results using PHP and put them into a JavaScript array.
This is what I have so far for the PHP (the JavaScript is fine just need to populate the array):
<?php
$mysqli = new mysqli('SERVER', 'U/NAME', 'P/WORD', 'DB');
if (!$mysqli)
{
die('Could not connect: ' . mysqli_error($mysqli));
}
if ($stmt = $mysqli->prepare("SELECT category.name FROM category")) {
$stmt->bind_result($name);
$OK = $stmt->execute();
}
while($stmt->fetch())
{
printf("%s, ", $name);
}
?>
Then I want to insert essentially each value using something like mysql_fetch_array ($name); (I know this is incorrect but just to show you guys what's going on in my head)
<script> -- this is the javascript part
(function() {
<?php while $stmt=mysql_fetch_array($name))
{
?>
var arrayObjects = [<?php stmt($name) ?>];
<?php }
?>
I can retrieve the results echoing out fine, I can manipulate the trie fine without MYSQL results, I just can't put them together.
In this case, what you're doing is looping through your result array, and each time you're printing out the line var arrayObjects = [<?php stmt($name) ?>];. However this doesn't convert between the PHP array you're getting as a result, and a javascript array.
Since you started doing it this way, you can do:
<?php
//bind to $name
if ($stmt = $mysqli->prepare("SELECT category.name FROM category")) {
$stmt->bind_result($name);
$OK = $stmt->execute();
}
//put all of the resulting names into a PHP array
$result_array = Array();
while($stmt->fetch()) {
$result_array[] = $name;
}
//convert the PHP array into JSON format, so it works with javascript
$json_array = json_encode($result_array);
?>
<script>
//now put it into the javascript
var arrayObjects = <?php echo $json_array; ?>
</script>
Use json_encode to turn your PHP array into a valid javascript object. For example, if you've got the results from your database in a php array called $array:
var obj = "<?php echo json_encode($array); ?>";
You can now use obj in your javascript code
For the auto-completion you can use the <datalist> tag. This is a relatively new feature in HTML5 (see support table) but the polyfill exists.
Fill the <option> tags in php when building the page and you a are done.

Categories