Skip to content
Advertisement

Populating a HTML table using JQUERY, PHP and AJAX

I am trying to populate a HTML table using JQUERY, AJAX and PHP code. When I run my code, my table is displayed but it is filled with ‘undefined’.

I have three pieces of code. Here is my HTML and jQuery:

var integer = $("#transfers_in").attr("name");
alert("integer: " + integer);
$.ajax('includes/test.php', {
  type: 'POST', // http method
  data: {
    dataType: 'json',
    myData: integer
  }, // data to submit
  success: function(response) {
    var len = response.length;
    for (var i = 0; i < len; i++) {
      var name = response[i].name;
      var amount = response[i].amount;
      var tr_str = "<tr>" +
        "<td align='center'>" + (i + 1) + "</td>" +
        "<td align='center'>" + name + "</td>" +
        "<td align='center'>" + amount + "</td>" +
        "</tr>";

      $("#money_in").append(tr_str);
    }
  }
});
<table id="money_in">
  <tr>
    <th>Name</th>
    <th>Amount(Million £)</th>
  </tr>
</table>

and here is my PHP Code:

<?php

if (isset($_POST['myData'])) {
    $integer = $_POST['myData'];

    if ($integer === "1"){
        include 'db_connection.php';

        // Create connection
        $conn = new mysqli($servername, $username, $password, $dbname);
        // Check connection
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }

        $return_arr = array();
        $query = "SELECT * FROM `money_in_19_20`";
        $result = mysqli_query($conn,$query);

        while($row = mysqli_fetch_array($result)){
            $name = $row['Name'];
            $amount = $row['Amount'];

            $return_arr[] = array("Name" => $name,
                              "Amount" => $Amount);
        }

        // Encoding array in JSON format
        echo json_encode($return_arr);
    }
}

The Json data is being received in the format of

{“Name”:”Hazard”,”Amount”:”103000000″}

Advertisement

Answer

You are returning object as Name,Amount and checking as name,amount

var name = response[i].name;
var amount = response[i].amount;

it should be

var name = response[i].Name;
var amount = response[i].Amount;
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement