Returning BD data with PHP and AJAX

Asked

Viewed 82 times

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.

  • 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.

1 answer

4

Do the following: return JSON to an array in PHP:

foreach ($query as $key => $fornecedorNome) {
    $json[] = $fornecedorNome;
}

print_r(json_encode($json));

And in Javascript do the parse:

var data = JSON.parse(xmlhttp.responseText);

The result will be like the print below, where you can iterate:

inserir a descrição da imagem aqui

The way you are doing it is returning an invalid JSON. Note that in your print there is no comma separation of objects. Returning in array form, commas are added automatically, as each object is an array item.

  • Don’t forget to change on the var supply lineName = date[i]. name; to var supplierName = date[i]; Since you did not assign a key to the array elements; To continue with the current loop you must do $json['name'][] = $supplierName; in php

  • No need. Each JSON item has an index (I added a print in the reply), so var fornecedorNome = data[i].nome will be the value of the key nome of each index.

  • Good morning Sam, I managed to make the answer appear correctly in my <p> TAG. Only, if I try to change to a <input> or a <select> I no longer have the functionality. In order to be able to play this result in a select or input with autocomplete, I have to change something in the code ?

  • Good morning. Depending on what you want to do, just change the way you treat the result. In the case of a select, you would create option instead of <p>, kind of: html += "<option value='qual valor?'>" + fornecedorNome + "</option>"

  • Got it. Finally, is there any way I can "sync" with the data? For example, instead of bringing only the "names", bring also the data of "id" and "cnpj", and as soon as I select the name of the vendor, for example, your ID and CNPJ automatically change to those of this selected vendor.

  • Yes, just bring them tb in the PHP JSON. But then you need to ask a new question for another case.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.