0

Trying to use javascript to read data that was retrieved using php 7 from a mongodb database. If I echo the $rows variable how do I capture that so I can process with javascript. Currently when I try to console the $rows data it only consoles an empty object {}.

php code:

<?php

try {

    $mng = new MongoDB\Driver\Manager("mongodb://localhost:27017");
    $query = new MongoDB\Driver\Query([]);

    $rows = $mng->executeQuery("testdb.cars", $query);
    echo json_encode($rows);
    /*
    foreach ($rows as $row) {

        echo "$row->name : $row->price\n";
    }
     */


} catch (MongoDB\Driver\Exception\Exception $e) {

    $filename = basename(__FILE__);

    echo "The $filename script has experienced an error.\n";
    echo "It failed with the following exception:\n";

    echo "Exception:", $e->getMessage(), "\n";
    echo "In file:", $e->getFile(), "\n";
    echo "On line:", $e->getLine(), "\n";
}
?>

index.php code:

<body>
    <script>
    function reqListener () {
    console.log(this.responseText);
    }

    var oReq = new XMLHttpRequest();
    oReq.onload = function() {

            console.log(this.responseText);
     };
    oReq.open("get", "get-data.php", true);

    oReq.send();
    </script>
</body>
jaysonn
  • 105
  • 9

1 Answers1

0

You can parse the php response to json:

var myArr = JSON.parse(this.responseText);

See full example here: https://www.w3schools.com/js/js_json_http.asp

Sergiu Ionescu
  • 341
  • 2
  • 7
  • Thank you for the feedback Sergiu but myArr is still empty {} – jaysonn Oct 04 '19 at 08:47
  • Check that the json response is returned when accessing the "get-data.php" script directly, if that is working, then open your index.php in the browser tab and make sure there are not network errors, you are not properly handling success, please see my link above. – Sergiu Ionescu Oct 04 '19 at 08:49