0

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.

Fahad Khan
  • 67
  • 1
  • 9
  • 1
    Hint: your response is an array of objects NOT one object. – Mikey Jun 14 '17 at 06:58
  • You are passing the option `dataType: 'json'` then in `success` option of ajax you should use response ( data here ) as an object. But you are treating as a string. – Pratik Soni Jun 14 '17 at 06:59
  • `if (data) { (data + '').length; }` - does nothing – Jaromanda X Jun 14 '17 at 06:59
  • @JaromandaX correct, I was trying to do the loop to get all values but got stuck in the current step. Forgot to remove this part. – Fahad Khan Jun 14 '17 at 07:01
  • @Mikey I am unable to get your hit. what am I doing wrong here then? – Fahad Khan Jun 14 '17 at 07:04
  • 1
    @FahadKhan `data["symbol"]` doesn't work because data isn't an object. `data.symbol` is nothing. `data` is an array of objects that have a symbol property. You need to be accessing symbol by first accessing each object in your array: `data[0].symbol`, `data[1].symbol`, etc. – Will Reese Jun 14 '17 at 07:08
  • 1
    Here's a quick tutorial I found for you to read: [Beginners: Javascript Objects and Arrays](http://www.appcelerator.com/blog/2013/04/beginners-javascript-objects-and-arrays-2/) Your case is the **fun part** – Mikey Jun 14 '17 at 07:09

2 Answers2

2

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.

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

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

        $("#output").append(
          "<tr><td>" + data[i].LastUpdated + "</td>" + 
          "<td>" + data[i].symbol + "</td></tr>" +
          "<td>" + data[i].sum + "</td></tr>"
        );
      }
    }
});
Will Reese
  • 2,801
  • 2
  • 15
  • 27
  • this works perfectly. Though one last thing, its is displaying everything in one row when I write like this: `for(var i = 0, len = data.length; i < len; i++) { $("#output").append(""); $("#output").append("" + data[i].LastUpdated + ""); $("#output").append("" + data[i].symbol + ""); $("#output").append("" + data[i].sum + ""); $("#output").append(""); }` – Fahad Khan Jun 14 '17 at 07:12
  • 1
    `append` doesn't work like you are just adding strings. `$("#output").append("")` will add the full element (closing tag included); Adding ``s after it is going to have them outside of your ``. I'll add another line of code to my answer to show you what to do. – Will Reese Jun 14 '17 at 07:15
  • perfect. I got what I wanted. Thanks a lot mate. – Fahad Khan Jun 14 '17 at 07:20
0

You have to change code as mentioned below.

From

data["symbol"]

to

data.symbol

Let me know if it not works.

Alex Mac
  • 2,970
  • 1
  • 22
  • 39
  • 3
    Those are [both the same thing](https://stackoverflow.com/a/4968448/1022914) in JavaScript. And `data` is an array not an object. – Mikey Jun 14 '17 at 07:01