I have searched and tried for hours but unsuccessful.
I have an existing page which displays simple data from DB using PHP in an HTML table. Now I want to implement AJAX functionality so that data is refreshed without page refresh.
I have implemented this solution, to my understanding, the AJAX call part is working and the values are getting refreshed as expected. but I am stuck in getting the values.
index.php (main page)
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js">
</script>
</head>
<body>
<h3>Output: </h3>
<table border="1" id="output"></table>
<script id="source" language="javascript" type="text/javascript">
$(function() {
update_content();
});
function update_content()
{
$.ajax({
url: 'query.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to query.php
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
if(data){
(data + '').length;
}
var temp = new Array();
$('#output').html("<tr><td>"+data["symbol"]+"</td></tr>");
}
});
setTimeout(function(){
update_content();
}, 1000);
}
</script>
</body>
</html>
query.php (used for AJAX call)
<?php
include('inc/connection.php');
# Main query
$sql = "
select LastUpdated, symbol, sum
from TheTable
";
$result = mysql_query($sql);
while($row = mysql_fetch_row($result)){
$table_data[]=array("LastUpdated"=>$row[0],"symbol"=>$row[1],"sum"=>$row[2]);
}
echo json_encode($table_data);
?>
If I run query.php directly in the browser, I see all the data in this format:[{"LastUpdated":"20170614","symbol":"AUD","sum":"20"},{"LastUpdated":"20170614","symbol":"AUD","sum":"10"}]
But on my main page, I see undefined
inside the table.
I'd ideally like to have all the values (using a JS loop in the above code may be) to display all the records fetched from DB (variable no. of records).
HINT/MODIFICATION
When I change:
$('#output').html("<tr><td>"+data["symbol"]+"</td></tr>");
to
$('#output').html("<tr><td>"+data[0]+"</td></tr>");
in index.php
AND
$table_data[]=array("LastUpdated"=>$row[0],"symbol"=>$row[1],"sum"=>$row[2]);
to
$table_data[]=$row;
in query.php,
then I get only first row as a string like
20170614,AUD,40
.
END HINT/MODIFICATION
I am sorry if that's a silly question/problem. I am new to jQuery and trying AJAX for first time.
P.S. I know mysql_* functions are deprecated and I am aware of the vulnerability.
Your help would be highly appreciated.