When outputting data, they are displayed in one line. How to make sure that every record is an object and all objects turn into an array?
<?php
require_once("db.php");
$query = $db->query('SELECT * FROM `dictdb`.`dictwords`');
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
echo "
id: " . $row['id'] . ",
engWord: " . $row['engwords'] . ",
rusWord: " . $row['ruswords'] ."
";
}
?>
test.js
$(document).ready(function () {
$(".btn-test").on("click", function () {
$.ajax({
url: "/src/php/tests.php",
type: "POST",
success: function (data) {
$(".test-word").html(data);
}
})
})
Because you're inserting plain text into HTML. That's meant to be with <tags> ignoring your whitespace (like line breaks).
Either load some reasonable HTML from PHP
## in PHP
...
echo "<p>
id: " . $row['id'] . ",<br>
engWord: " . $row['engwords'] . ",<br>
rusWord: " . $row['ruswords'] ."<br>
</p>";
...
Or, better, work with JSON
## in PHP
...
$results = [];
while ($row = $query->fetch(PDO::FETCH_ASSOC))
$results[] = $row;
header('Content-Type: application/json');
echo json_encode($results);
...
## in JS
$.ajax('/src/php/tests.php')
.done(data => { // use .success for older jQuery versions
let formatedJSON = JSON.stringify(data, null, 2);
$(".test-word").html(`<pre>${formatedJSON}</pre>`);
});
Put the desired HTML tags in the data you echo.
echo "<br>
id: " . $row['id'] . ",<br>
engWord: " . $row['engwords'] . ",<br>
rusWord: " . $row['ruswords'] ."<br>
";
Your echo does not produce a JSON object. You would need to do something like:
<?php
require_once("db.php");
$query = $db->query('SELECT * FROM `dictdb`.`dictwords`');
$response = [];
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$response[] = [
'id' => $row['id'],
'engWord' => $row['engwords'],
'rusWord' => $row['ruswords'],
];
}
echo json_encode($response);
This would produce a JSON object similar to (if you had 2 results returned from DB):
[
{
id: 'YourID',
engWord: 'Your Eng Word',
rusWord: 'Your Rus Word',
}, {
id: 'YourID',
engWord: 'Your Eng Word',
rusWord: 'Your Rus Word',
},
]
Rather than try to parse HTML, i'd highly recommend using a JSON response.