How to Iterate through Object in JavaScript and PHP - javascript

I am having to solve a problem involving code in both JS and PHP. For some reason, whenever this code executes, it puts the first entry in all the rows of the table instead of iterating through each entry and putting all of them in the rows. I would appreciate someone's help in giving me insights into how to fix this issue. Can this be fixed with just a "for in" loop? Thanks in advance.
<?php include('../../functions.php');
$query = "
SELECT
*
FROM
plobby
LEFT JOIN users ON users.UID = plobby.UID
WHERE
`LID` = '". preg_replace("/[^A-Za-z0-9 ]/", '', $_POST['id']) ."';
";
$sql = "SELECT COUNT(`LID`) AS `x` FROM `snipe`.`plobby` WHERE LID = '".$_POST['id']."';";
$result = $db->query($query);
$rst = $db->query($sql);
$cnt = 0;
if($rst->num_rows > 0)
while($row = $rst->fetch_assoc())
$cnt = $row["x"];
if ($result->num_rows > 0)
for($i = 1;$i<= $cnt;$i++)
echo json_encode($result->fetch_assoc());
else
echo json_encode([]);
?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Here is the object to which the above loop is referring:
<script type="text/javascript">
var state = {};
for($i = 1;$i <= <?php echo getLobbytPlayers($_GET['id']);?>;$i++ ){
var reloadTable = function (data) {
if ($.data(state) == $.data(data)) {
return;
}
$('#js-lobby-table').empty();
$.each(data, function (rowNumber, rowData) {
var row = $('<tr>');
console.log(data);
// Player
row.append($('<td>', {
'html': data.eName
}));
// Status
row.append($('<td>', {
'html': data.gameID == "000" ? 'waiting' : 'ingame'
}));
// Win %
row.append($('<td>', {
'html': 'TODO'
}));
// Games
row.append($('<td>', {
'html': 'TODO'
}));
// K/D
row.append($('<td>', {
'html': 'TODO'
}));
$('#js-lobby-table').append(row);
});
// Set the current table state.
state = data;
};
}
setInterval(function () {
$.ajax({
type: 'POST',
url: '/lobby/api/table.php',
data: {
id: '<?= $_GET['id'] ?>'
},
success: reloadTable,
dataType: 'json'
});
}, 10);
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

You shouldn't call json_encode() multiple times. The response has to contain a single JSON object, not multiple objects. You need to put all the results in an array, and call json_encode() on that array at the end.
There's also no need to get the count first. Just call fetch_assoc() until you get all the results.
<?php include('../../functions.php');
$query = "
SELECT
*
FROM
plobby
LEFT JOIN users ON users.UID = plobby.UID
WHERE
`LID` = '". preg_replace("/[^A-Za-z0-9 ]/", '', $_POST['id']) ."';
";
$result = $db->query($query);
$rows = [];
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
echo json_encode($rows);
?>

Related

dataTable switch to next page with no entry - paging issue

I want to display records from mysql-database on a monitor using a table from dataTables with serverside paging. Maximum rows per side should be 14. When filling up the database and reaching the 14th row the table already starts paging (!) showing the message "no matching records found".... then it switches back to the page with 1-14 rows....
Any clue what I am doing wrong here?
My code is as follows:
php-page creating json array
//fetch.php
$connect = new PDO("mysql:host=localhost;dbname=eflightbook", "root", "");
$column = array("usersName", "usersFirstname", "fldirector");
$query = "SELECT usersName, usersFirstname, TIME(date), fldirector, t1.*
FROM users, flightbook t1
WHERE usersLoginStatus <> 'false'
AND id = anw_id
AND t1.date = (SELECT MAX(t2.date)
FROM users, flightbook t2
WHERE t2.anw_id = t1.anw_id)
";
if(isset($_POST['order']))
{
$query .= 'ORDER BY '.$column[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].' ';
}
else
{
$query .= 'ORDER BY TIME(date) ASC ';
}
$query1 = '';
if($_POST['length'] != -1)
{
$query1 = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connect->prepare($query);
$statement->execute();
$number_filter_row = $statement->rowCount();
$result = $connect->query($query . $query1);
$data = array();
foreach($result as $row)
{
$sub_array = array();
$sub_array[] = $row['usersName'];
$sub_array[] = $row['usersFirstname'];
$sub_array[] = $row['TIME(date)'];
$sub_array[] = ($row['fldirector'] == "1") ? "✔" : "";
$data[] = $sub_array;
}
function count_all_data($connect)
{
$query = "SELECT anw_id, usersName, usersFirstname, TIME(date), fldirector, t1.*
FROM users, flightbook t1
WHERE usersLoginStatus <> 'false'
AND id = anw_id
AND t1.date = (SELECT MAX(t2.date)
FROM users, flightbook t2
WHERE t2.anw_id = t1.anw_id)
";
$statement = $connect->prepare($query);
$statement->execute();
return $statement->rowCount();
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => count_all_data($connect),
"recordsFiltered" => $number_filter_row,
"data" => $data
);
echo json_encode($output);
?>
**Monitor html/php Page**
<script>
// Active Pilots Table
$(document).ready(function(){
function load_data(start, length)
{
var dataTable = $('#datatable').DataTable({
"processing" : false,
"serverSide" : true,
"pageLength" : 14,
"lenghtChange" : false,
"language": {
"emptyTable": "** kein Eintrag **"},
"columnDefs": [
{
targets: -1,
className: 'dt-body-center'
}],
"responsive" : false,
"autoWidth" : false,
"ordering" : false,
"searching" : false,
"scrollCollapse" : true,
"binfo" : false,
"bFilter" : false,
"bLengthChange" : false,
dom: "lfrti",
"order" : [],
"retrieve": true,
"ajax" : {
url:"activep.php",
method:"POST",
data:{start:start, length:length}
},
"drawCallback" : function(settings){
var page_info = dataTable.page.info();
console.log(page_info);
}
});
}
load_data();
var table = $('#datatable').DataTable();
setInterval(function(){
var info = table.page.info();
if (info.start < info.end) {
var page_number = (info.page < info.pages) ? info.page + 1 : 1;
}
else {
page_number = 0;
}
;
table.page(page_number).draw(false);
}, 6000);
});
Your problem is here:
var info = table.page.info();
if (info.start < info.end) {
var page_number = (info.page < info.pages) ? info.page + 1 : 1;
}
else {
page_number = 0;
}
;
table.page(page_number).draw(false);
There are two issues. First, to specifically answer your question: assuming info.page is equal to info.pages (which means you have one page of records) you are setting the page number to 1, but that property is indexed at 0 (and also documentation here), so you are actually forcing it to the second page:
var page_number = (info.page < info.pages) ? info.page + 1 : 1;
and then later, you pass that page number value to your table:
table.page(page_number).draw(false);
And the second issue (which is not the cause of your specific problem but is definitely problematic in terms of variable scope): you define the page_number variable inside the scope of the if statement but then use it outside of that scope. That type of variable declaration should be avoided. You should declare the variable outside of the if statement.

How to prevent users to search null/space value because it keeps returning all values from database

When I search null or space values, all the results from database come to my html table.
I wanted to prevent users to search null values or space values.
I tried this post, but now helped me, How to prevent a database search from running on an empty string?
Here is the backend script-
<?php
//fetch.php
$connect = new PDO("mysql:host=localhost;dbname=searchv3", "root", "");
$output = '';
$query = '';
$data = [];
if(isset($_POST["query"]))
{
$search = str_replace(",", "|", $_POST["query"]);
$query = "
SELECT * FROM number_list
WHERE IMSI REGEXP '".$search."'
OR Mobile_no REGEXP '".$search."'
OR Backup_date REGEXP '".$search."'
OR Sr REGEXP '".$search."'
";
}
else
{
$query = "
SELECT * FROM number_list order by Sr DESC LIMIT 50;
";
}
$statement = $connect->prepare($query);
$statement->execute();
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
$data[] = $row;
}
echo json_encode($data);
$connect = null;
?>
I will share front-end jav script as well-
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"fetch_numberlist.php",
method:"POST",
data:{query:query},
dataType:"json",
success:function(data)
{
$('#total_records').text(data.length);
var html = '';
if(data.length > 0)
{
for(var count = 0; count < data.length; count++)
{
html += '<tr>';
html += '<td>'+data[count].Sr+'</td>';
html += '<td>'+data[count].IMSI+'</td>';
html += '<td>'+data[count].Mobile_no+'</td>';
html += '<td>'+data[count].Backup_date+'</td>';
}
}
else
{
html = '<tr><td colspan="4">No Data Found</td></tr>';
}
$('tbody').html(html);
}
})
}
$('#search').click(function(){
var query = $('#tags').val();
load_data(query);
});
})
</script>
...
$data = [];
// `??` operator returns value if isset needed post element, else use empty string
// trim - remove start and ending spaces from string.
// So it return empty string if user input only space
$post_query = trim($_POST["query"] ?? '');
if($post_query)
{
$search = str_replace(",", "|", $post_query);
...

Passing the query count in javascript variable

See i have below Code in my javascript
var itemCount = 5, activeScroll = 0, countScroll = 0;
setInterval(function() {
if(countScroll == (itemCount - 2))
{
activeScroll = 0;
countScroll = 0;
$('#list').animate({scrollTop: 0});
}
else
{
activeScroll += 250;
countScroll += 1;
$('#list').animate({scrollTop: activeScroll});
}
}, 2000);
and my query string in php code is
$userads = mysql_query("SELECT * FROM user_ads ORDER BY `user_addate` DESC");
$adcount = mysql_num_rows($userads);
i am trying to assign value of $adcount in javascript variable var itemCount;
query is running in test.php and javascript is scroller.js.
Please help me .
You can output javascript by test.php:
<?php
$userads = mysql_query("SELECT * FROM user_ads ORDER BY `user_addate` DESC");
$adcount = mysql_num_rows($userads);
?>
<script type='text/javascript'>
var itemCount = <?php echo $adcount; ?>;
setupTimer(itemCount);
</script>
Make sure the scroller.js defines the function setupTimer(itemCount) that performs the task you want, instead of firing right away.
First you need to request the value from the server. Then you can assign it.
var itemCount;
setInterval(function() {
$.get('test.php', function(response) {
itemCount = response.itemCount;
// you scroll logic here
}, 'json');
}, 2000);
In test.php you should output the value by something like this:
$output = array(
"itemCount" => $adcount
);
print json_encode($output);
in scroller.js type this code:
$.ajax("test.php", {
type: 'post',
data: {
count:itemCount
},
sync: true,
success: function (adcount) {
itemCount=adcount;
}
});
in test.phptype this code:
if (isset($_POST['count']))
{
echo $adcount;
exit;
}
notice:you should use jquery file in your script for ajax

How do I display multiple stacked columns for each date range in an stacked Bar

Essentially, the purpose is to compare what categories of tasks each member on my team is performing on a weekly basis.
and I would like to add number of Week underneath the Axes instead of 1.0 , 2.0 and 3.0 .
I am getting wrong result as its only showing 1 for excellent and for all week1, week2, week3, week4
I selected starting day 1/12/2014 and the end date is 31/12/2014 so I was expecting to have 1 for bad and two for good and three for excellent.
This is my PHP code
<?php>
$result = mysqli_query($con,"SELECT * FROM `employees` WHERE `Date` BETWEEN '" . $_POST
['start'] . "' AND '" . $_POST ['end'] . "' ") or die ("Error: ".mysqli_error($con));
$Levels = 0;
$Levelscounter=0;
$countergood=0;
$counterbad=0;
while($row = mysqli_fetch_array($result))
{
$answer = $row['level'];
$bad = 'bad';
$good='good';
$excellent='excellent';
if ($answer == $bad)
{
$counterbad++;
}
if($answer == $good)
{
$countergood++;
}
if($answer == $excellent)
{
$counterexcellent++;
}
$Levelscounter;
}
mysqli_close($con);
?>
Here is my JavaScript Code:
<script type="text/javascript">
(function($) {
var series = [{
data: [[ 1,<?php echo $counterbad; ?>] ],
valueLabels: {
show: true,
valign: 'middle'
} ,
label: "Low"
},
{
data: [[1,<?php echo $countergood; ?>]],
valueLabels: {
show: true,
valign: 'middle'
} ,
label: "Medium"
}, {
data: [[1,<?php echo $counterexcellent; ?>]],
valueLabels: {
show: true,
valign: 'middle'
} ,
label: "High"
}];
var options = {
xaxis: {
minTickSize: 1
},
series: {
bars: {
show: true,
barWidth: .8,
align: "center"
},
stack: true
}
};
$.plot("#placeholder", series, options);
})(jQuery);
</script>
I got the levels displayed in the stacked chart and it is working fine regarding from the start and end date I select but I could display this result as a weekly result.
I would like to get ideas what do I need to add ? Any ideas please ?
Is there a function in PHP that sort out this ?
Thank you.
Updating
As you can see in the image numbers on each series related to bad, good, excellent.
red for bad and good for blue and yellow for excellent.
To add weeks/textual data underneath the columns you have to add the library's categories file jquery.flot.categories.min.js to your javascript assets.
If i understand you correctly you want the chart to look like this
Javascript
You need to add these files in
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="jquery.flot.min.js"></script>
<script src="jquery.flot.categories.min.js"></script>
<script src="jquery.flot.stack.min.js"></script>
and initialize the library we will talk about $output after this code
<div id="placeholder" style="width:818px;height:413px" ></div>
<script type="text/javascript">
$(function() {
var series = [<?php echo $output; ?>];
$.plot("#placeholder", series, {
series: {
stack:true,
lines:{fill:true,show:false,steps:false},
bars: {
show: true,
barWidth: 0.8,
align: "middle",
},
},
xaxis: {
mode: "categories",
minTickSize: 1
}
});
});
PHP
First you need to query the database to find the date between the specified dates, after getting the result you have to sort the data for each week in an array
For instance week One => 'good','good','bad','bad', 'week two' => and so on ...
after that you can use array_count_values() to count the number of occurrences and build
the charts column.
I simplified the code using functions to make it easier for you
<?php
$con = mysqli_connect("localhost", 'root','','your db');
function getChartData($con, $startDate, $endDate){
$startDate = date("Y-m-d H:i:s", strtotime($startDate));
$endDate = date("Y-m-d H:i:s", strtotime($endDate));
$query = "SELECT * FROM `employees` WHERE `date` BETWEEN '$startDate' AND '$endDate'";
$result = mysqli_query($con, $query) or die ("Error: ".mysqli_error($con));
// a multidimenional array containing each week with it's
$weeksData = [];
// Group each week with it's data
while($row = mysqli_fetch_array($result)){
$weekNumber = date("W", strtotime($row['date']));
if(isset($weeksData[$weekNumber]))
{
$weeksData[$weekNumber][] = $row['level'];
}
$weeksData[$weekNumber][] = $row['level'];
}
// reset array indexes and sort the array
sort($weeksData);
$data = array();
// using array_count_values to count the number of (good, bad and excellent)
foreach ($weeksData as $key => $week) {
$data[$key] = array_count_values($week);
}
// return all the weeks with number of (good, bad and excellent) occurences
return $data;
}
// build the javascript object {data:['week num', occuerences]}
function buildColumn($data,$label, $numberOfWeeks)
{
$data = array_column($data,strtolower($label));
$balance = $numberOfWeeks - count($data);
if($balance !=0){
for($i=1;$i<=$balance;$i++) {
$data[] = 1;
}
}
$string = '{data: [';
foreach ($data as $key => $value) {
$weekNumber = $key+1;
$string .= '["Week '.$weekNumber.'",'.$value.'],';
}
$string = rtrim($string, ',');
$string .= "],valueLabels: {show: true,valign: 'middle'},label: '$label'}";
return $string;
}
function getNumberofWeeks($startDate, $endDate){
$weeks = array();
$period = new DatePeriod(new DateTime($startDate),
DateInterval::createFromDateString('+1 day'),new DateTime($endDate)
);
foreach ( $period as $dt ) {
$weeks[] = $dt->format( 'W' );
}
return count(array_unique($weeks));
}
now you can easily use these functions like this
$numberOfWeeks = getNumberofWeeks($_POST['start'],$_POST['end']);
// get data of the last number of weeks
$chartData = getChartData($con, $_POST['start'],$_POST['end']);
// bulding columns data for each occurence
$badColumn = buildColumn($chartData,'Bad', $numberOfWeeks);
$goodColumn = buildColumn($chartData,'Good', $numberOfWeeks);
$excellentColumn = buildColumn($chartData,'Excellent', $numberOfWeeks);
// output {data: ...}, {data: ...},{data:....}
$output = "$excellentColumn , $goodColumn , $badColumn";
Full working Example
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="jquery.flot.min.js"></script>
<script src="jquery.flot.categories.min.js"></script>
<script src="jquery.flot.stack.min.js"></script>
</head>
<body>
<?php
$con = mysqli_connect("localhost", 'root','','your db');
function getChartData($con, $startDate, $endDate){
$startDate = date("Y-m-d H:i:s", strtotime($startDate));
$endDate = date("Y-m-d H:i:s", strtotime($endDate));
$query = "SELECT * FROM `employees` WHERE `date` BETWEEN '$startDate' AND '$endDate'";
$result = mysqli_query($con, $query) or die ("Error: ".mysqli_error($con));
// a multidimenional array containing each week with it's
$weeksData = [];
// Group each week with it's data
while($row = mysqli_fetch_array($result)){
$weekNumber = date("W", strtotime($row['date']));
if(isset($weeksData[$weekNumber]))
{
$weeksData[$weekNumber][] = $row['level'];
}
$weeksData[$weekNumber][] = $row['level'];
}
// reset array indexes and sort the array
sort($weeksData);
$data = array();
// using array_count_values to count the number of (good, bad and excellent)
foreach ($weeksData as $key => $week) {
$data[$key] = array_count_values($week);
}
// return all the weeks with number of (good, bad and excellent) occurences
return $data;
}
// build the javascript object {data:['week num', occuerences]}
function buildColumn($data,$label, $numberOfWeeks)
{
$data = array_column($data,strtolower($label));
$balance = $numberOfWeeks - count($data);
if($balance !=0){
for($i=1;$i<=$balance;$i++) {
$data[] = 1;
}
}
$string = '{data: [';
foreach ($data as $key => $value) {
$weekNumber = $key+1;
$string .= '["Week '.$weekNumber.'",'.$value.'],';
}
$string = rtrim($string, ',');
$string .= "],valueLabels: {show: true,valign: 'middle'},label: '$label'}";
return $string;
}
function getNumberofWeeks($startDate, $endDate){
$weeks = array();
$period = new DatePeriod(new DateTime($startDate),
DateInterval::createFromDateString('+1 day'),new DateTime($endDate)
);
foreach ( $period as $dt ) {
$weeks[] = $dt->format( 'W' );
}
return count(array_unique($weeks));
}
// the number of weeks that you want to display in the chart
$numberOfWeeks = getNumberofWeeks($_POST['start'],$_POST['end']);
// get data of the last number of weeks
$chartData = getChartData($con, $_POST['start'],$_POST['end']);
// bulding columns data for each occurence
$badColumn = buildColumn($chartData,'Bad', $numberOfWeeks);
$goodColumn = buildColumn($chartData,'Good', $numberOfWeeks);
$excellentColumn = buildColumn($chartData,'Excellent', $numberOfWeeks);
// output {data: ...}, {data: ...},{data:....}
$output = "$excellentColumn , $goodColumn , $badColumn";
?>
<div id="placeholder" style="width:818px;height:413px" ></div>
<script type="text/javascript">
$(function() {
var series = [<?php echo $output; ?>];
$.plot("#placeholder", series, {
series: {
stack:true,
lines:{fill:true,show:false,steps:false},
bars: {
show: true,
barWidth: 0.8,
align: "middle",
},
},
xaxis: {
mode: "categories",
minTickSize: 1
}
});
});
</script>
</body>
</html>
Edit
Just replace these two functions to make it compatible with dd/mm/yyyy
function getChartData($con, $startDate, $endDate){
$startDate = explode('/', $startDate);
$startDate = $startDate[1] . '/' . $startDate[0] . '/' . $startDate[2];
$endDate = explode('/', $endDate);
$endDate = $endDate[1] . '/' . $endDate[0] . '/' . $endDate[2];
$startDate = date("Y-m-d H:i:s", strtotime($startDate));
$endDate = date("Y-m-d H:i:s", strtotime($endDate));
$query = "SELECT * FROM `employees` WHERE `date` BETWEEN '$startDate' AND '$endDate'";
$result = mysqli_query($con, $query) or die ("Error: ".mysqli_error($con));
// a multidimenional array containing each week with it's
$weeksData = [];
// Group each week with it's data
while($row = mysqli_fetch_array($result)){
$weekNumber = date("W", strtotime($row['date']));
if(isset($weeksData[$weekNumber]))
{
$weeksData[$weekNumber][] = $row['level'];
}
$weeksData[$weekNumber][] = $row['level'];
}
// reset array indexes and sort the array
sort($weeksData);
$data = array();
// using array_count_values to count the number of (good, bad and excellent)
foreach ($weeksData as $key => $week) {
$data[$key] = array_count_values($week);
}
// return all the weeks with number of (good, bad and excellent) occurences
return $data;
}
and
function getNumberofWeeks($startDate, $endDate){
$startDate = explode('/', $startDate);
$startDate = $startDate[1] . '/' . $startDate[0] . '/' . $startDate[2];
$endDate = explode('/', $endDate);
$endDate = $endDate[1] . '/' . $endDate[0] . '/' . $endDate[2];
$diff = strtotime($startDate, 0) - strtotime($endDate, 0);
return str_replace('-','', (int)floor($diff / 604800));
}

Call multiple functions from AJAX and return separate data

I'm trying to get two distinct results from AJAX calls. I pass in _functionToRun to the PHP file, which uses a switch statement to determine which function to run.
In the PHP file, I echo out two different arrays of words... newQuestWords() should only return some of the words. parseHoveredText() should return all vocab in the database.
Yet it seems when I echo out both, just all of the vocab is returned...
For example, in the JavaScript, log(hoveredWords[i]); should show all of the vocab available in the database, as returned from `parseHoveredText() function, but it doesn't show anything.
Why is that?
JavaScript:
$(document).ready(function() {
//initially append words to word bank
$.getJSON("php/Quests.php", { "_questNum" : questNum, "_functionToRun" : 1},
function(returned_data) {
wordsArray = returned_data;
$.each(wordsArray, function(key, value) {
$(".wordBank_Words").append("<span class='bankword' data-display-word='" + key + "' ><b>" + key + "</b>: " + value + "</span><br/>");
}
);
});
//get all chinese/english words for hover over translation
$.getJSON("php/Quests.php", {"_functionToRun" : 2},
function(returned_data) {
hoveredWords = returned_data;
for (var i = 0; i < hoveredWords.length; i++) {
log(hoveredWords[i]);
}
});
PHP:
<?php
//if user's input is correct, increment task number, get next vocabulary
$functionToRun = (isset($_GET['_functionToRun'])) ? $_GET['_functionToRun'] : 1;
parseHoveredText();
switch ($functionToRun)
{
case 1:
newQuestWords();
break;
case 2:
parseHoveredText();
break;
default:
echo "defaulted...";
}
function newQuestWords () {
include 'DbConnect.php';
$questNumber = (isset($_GET['_questNum'])) ? $_GET['_questNum'] : 1;
$qry =
"SELECT t.*, v.*
FROM task t
INNER JOIN vocabtask vt ON (t.id = vt.taskid)
INNER JOIN vocab v ON (v.id = vt.vocabid)
WHERE vt.taskid = " . $questNumber;
$sql = $mysqli->query($qry);
$wordsArray = array();
while ($row = $sql->fetch_assoc()) {
$wordsArray[$row['chinese']] = $row['english'];
}
mysqli_close($mysqli);
echo json_encode($wordsArray);
}
function parseHoveredText () {
include 'DbConnect.php';
$qry =
"SELECT v.*
FROM vocab v";
$sql = $mysqli->query($qry);
$hoveredWords = array();
while ($row = $sql->fetch_assoc()) {
$hoveredWords[$row['chinese']] = $row['english'];
}
mysqli_close($mysqli);
//return Chinese and English Words
echo json_encode($hoveredWords);
}
?>
Dump return_data, it is json object not an array you can iterate. You can iterate through it this way
...
function(returned_data) {
for (word in returned_data) {
console.log(word);
}
}
...
Or with $.each
...
$.each(returned_data, function(key, value) {
console.log(value);
}
...

Categories