Fahad Khan Fahad Khan -4 years ago 36
PHP Question

Unable to access AJAX Response Data through jQuery

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)

<script type="text/javascript"
<h3>Output: </h3>

<table border="1" id="output"></table>

<script id="source" language="javascript" type="text/javascript">
$(function() {

function update_content()
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
(data + '').length;
var temp = new Array();
}, 1000);

query.php (used for AJAX call)


# Main query
$sql = "
select LastUpdated, symbol, sum
from TheTable

$result = mysql_query($sql);

while($row = mysql_fetch_row($result)){
echo json_encode($table_data);

If I run query.php directly in the browser, I see all the data in this format:

But on my main page, I see
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).


When I change:




in index.php





in query.php,

then I get only first row as a string like



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.

Answer Source

When you update your data table you'll probably want to just rebuild the table. In your callback function, you need to loop through the array and add new rows to the table.

  url: 'query.php', //the script to call to get data          
  dataType: 'json', //data format      
  success: function(data) {
      if (!Array.isArray(data) || !data.length) {

      $("#output").empty(); //clear old table data
      for(var i = 0, len = data.length; i < len; i++) {

          "<tr><td>" + data[i].LastUpdated + "</td>" + 
          "<td>" + data[i].symbol + "</td></tr>" +
          "<td>" + data[i].sum + "</td></tr>"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download