0
I’m a beginner with PHP and I’m having a problem returning data from BD to present it in the Front-End with AJAX and JS. I don’t think I know how to handle the data, because until the browser console, the data is returned correctly, but when trying to put them in front, I have a "Undefined" as a response. Can anyone tell me where I’m going wrong ?
My code in index.php:
<!doctype html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Testando API</title>
</head>
<body>
<p id="fornecedorNome"></p>
<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/script.js"></script>
</body>
</html>
My code that pulls the data:
<?php
$servidor = 'localhost';
$usuario = 'root';
$senha = '';
$dbname = 'testevip';
$connect = mysqli_connect($servidor, $usuario, $senha, $dbname);
$result = "SELECT nome from fornecedores ORDER BY nome ASC LIMIT 30";
$query = mysqli_query($connect, $result);
foreach ($query as $key => $fornecedorNome) {
print_r(json_encode($fornecedorNome));
}
?>
My code in JS / AJAX:
function loadDados() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if (xmlhttp.status == 200) {
var data = xmlhttp.responseText;
console.log(data);
var html = "";
for (var i = 0; i < data.length; i++){
var fornecedorNome = data[i].nome;
html += "<p>" + fornecedorNome + "</p>";
}
document.getElementById("fornecedorNome").innerHTML = html;
}
else if (xmlhttp.status == 400) {
alert('There was an error 400');
}
else {
alert('something else other than 200 was returned');
}
}
};
xmlhttp.open("GET", "API.php", true);
xmlhttp.send();
}
loadDados();
And finally the answer I have in my browser: http://prntscr.com/nqxvyf
I thank you in advance for any help provided, thank you very much !
Can you print the return of the console? Sometimes the answer is coming nested so that your is not going through the indexes correctly. Apparently you have an array of arrays containing the names you need, in your PHP code you try to use json_encode only after interacting all your data mass.
– Leandro Paiva
I believe the error is due to the print_r loop you are making. Try to change the foreach ($query as $key => $vendorNome) {print_r(json_encode($vendorName);} by echo json_encode($query) and see if it works; then you will receive the full object to make your interactions in the JS loop.
– Marcus Italo