pass php value to js giving error

Asked

Viewed 307 times

-1

<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}

table, td, th {
border: 1px solid black;
padding: 5px;
}

th {text-align: left;}
</style>
</head>
<body>

<?php
$q = intval($_GET['q']);

$con = mysqli_connect('localhost','peter','abc123','my_db');
if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"banco_dados");
$sql="SELECT * FROM usuario WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);

echo "<table>
<tr>
<th>nome</th>
<th>snome</th>
<th>idade</th>
<th>cidade</th>
<th>estado</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['nome'] . "</td>";
echo "<td>" . $row['snome'] . "</td>";
echo "<td>" . $row['idade'] . "</td>";
echo "<td>" . $row['cidade'] . "</td>";
echo "<td>" . $row['estado'] . "</td>";
echo "</tr>";
$json[] = $row;
}
echo "</table>";
mysqli_close($con);

$teste = $row['nome'];

?>
 <script type="text/javascript">
   var dados = <?php echo json_encode($json)?>;
   alert(dados[2].nome);
  </script>

</body>
</html>

see in the last 8 lines returns me an Alert more without data in the variables only returns it is that I need to work with this data in a js understand.

you know how I can pass these vlores to the js?

  • 2

    The important question here is: why do you want to display a Javascript alert with the HTML <td> tag? Or, if this alert should be inside while to get the $Row['name'], why do you want to display a Javascript alert for each line of the query? Makes no sense.

  • is that I want to use this data in a user panel the Alert is just to know if you have how to pass the value pro js.

2 answers

1

The problem is that you are setting $teste = $row['nome']; outside the while, that is, there is no longer the variable $row['nome']. Ideally you set the variable outside the while (before), and within it, assign a value. Thus:

$teste = "Erro ao pegar o valor"; // Cria uma variável com um valor inicial
while($row = mysqli_fetch_array($result)) {
  echo "<tr>";
  echo "<td>" . $row['nome'] . "</td>";
  echo "<td>" . $row['snome'] . "</td>";
  echo "<td>" . $row['idade'] . "</td>";
  echo "<td>" . $row['cidade'] . "</td>";
  echo "<td>" . $row['estado'] . "</td>";
  echo "</tr>";
  $teste = $row['nome']; // Atribui um novo valor para a variável
}

Thus, even if the query goes wrong, the variable $teste will exist, and it will automatically display a message saying that the query was not successful.

  • even so does not pass the value to the friend Alert.

  • Why should you use the variable $teste in the alert...

  • the truth is that I want to pass the value of the variable php pro javascript either in Alert or simply in the variable js.

1


Well, if I understand your question correctly, you need to take the data that comes from the back end and use it in a js function, right?

One option is to generate a JSON with this data and manipulate it according to your needs. I’ll give you an example of what your while loop would look like in php:

$json = array();
while($row = mysqli_fetch_array($result)) {
  echo "<tr>";
  echo "<td>" . $row['nome'] . "</td>";
  echo "<td>" . $row['snome'] . "</td>";
  echo "<td>" . $row['idade'] . "</td>";
  echo "<td>" . $row['cidade'] . "</td>";
  echo "<td>" . $row['estado'] . "</td>";
  echo "</tr>";
  $json[] = $row; //adiciona o row dentro do objeto json
}

After that, to make this object accessible in js, open a script tag and write:

var dados = <?php echo json_encode($json)?>;

Thus, you can access any value using:

alert(dados[0].nome);

Replace 0 with the Row number you want to use. The json object is independent of the table that was printed in HTML, so you don’t have to worry if you need to change something in it.

  • friend is not returning me anything in that Alert Voce told me, so I put so to see if it worked but returned null, Alert(data); but your Alert does not seem to work no.

  • 1

    Check the source code of the page if the data variable is being set correctly within the script tag. Basically you are printing a PHP array for a JSON object.

  • Chrome console says that the number "0" is null (Uncaught Typeerror: Cannot read Property '1' of null ) the Alert thus Alert(data[1].name;) returns null the javascript is running inside the tags normally but Alert is wrong. Is that we are trying to access from a wrong mode?

  • 1

    Open the page source code (Ctrl+u on Chrome) and update your response with the value being printed on the line: var data = <?php echo json_encode($json)?>;

  • returns this >></tr></table> <script type="text/javascript"> var data = null; Alert(data[2].name); </script> means that json is not with php data?

  • Exactly. The json_encode function basically transforms an array into a JSON format string. See if your query is returning results.

Show 1 more comment

Browser other questions tagged

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