Insert PHP in Javascript [closed]

0

Hello

I need to get the results of a SELECT in PHP and display in a ALERT within a function in JAVASCRIPT , where running JAVASCRIPT runs PHP and WHILE . How can I do ? I'm confused about the keys and the SCRIPT tag.

<script>

function jsLoad( ) 
{

$("#preload").hide();
continuar_produtos();

}

function continuar_produtos()
{
</script>

<?php


//1. Dados de conex?o
$host = "localhost";
$bd = "bancodedadosr";
$usr = "root";
$psw = "12345";

//3. Cria a conex?o
$conn = new mysqli($host, $usr, $psw, $bd);
if ($conn->connect_error) 
{
die("A conex?o falhou, consulte o suporte: " . $conn->connect_error);
} 
//4. D? um SELECT no Banco de Dados utilizando os dados recebidos via POST
$sql = "SELECT id, nome, tipo, imagem, modelo FROM produtos";
$result = $conn->query($sql);
//5. D? um while e armazena na vari?vel o valor dos dados
if ($result->num_rows > 0)
{

while($row = $result->fetch_assoc())
{
//6.5. Criar n? filho (resultado)
$id = $row['id'];
$nome = $row['nome'];
$tipo = $row['tipo'];
$imagem = $row['imagem'];

?>

<script>

alert("<?php echo $nome; ?>");

</script>
   
<?php
 }
}
   
?>

<script>

}

function jsDivStore()

{

$("#store").show();

$( "#store" ).load( "new-product.php", function() {

});

}

Issue resolved: Working code:

<html>
<head>
<title></title>
</head>
<body onload="continuar_produtos()">
<script>
function jsLoad( ) 
{
$("#preload").hide();
continuar_produtos();
}

function continuar_produtos()
{

<?php
//1. Dados de conex?o
$host = "localhost";
$bd = "bancodedadosr";
$usr = "root";
$psw = "12345";

//3. Cria a conex?o
$conn = new mysqli($host, $usr, $psw, $bd);
if ($conn->connect_error) 
{
	die("A conex?o falhou, consulte o suporte: " . $conn->connect_error);
} 
//4. D? um SELECT no Banco de Dados utilizando os dados recebidos via POST
$sql = "SELECT id, nome, tipo, imagem, modelo FROM produtos";
	$result = $conn->query($sql);
	//5. D? um while e armazena na vari?vel o valor dos dados
	if ($result->num_rows > 0)
	{

	  while($row = $result->fetch_assoc())
	 {
	   $id = $row['id'];
	   $nome = $row['nome'];
	   $tipo = $row['tipo'];
	   $imagem = $row['imagem'];
	   $modelo = $row['modelo'];
?>

alert("<?php echo $nome; ?>");

<?php
	 }
	}
?>
}

function jsDivStore()
{
$("#store").show();

$( "#store" ).load( "new-product.php", function() {

});

}
</script>
</body>
</html>

Thank you

    
asked by anonymous 02.10.2017 / 15:45

3 answers

3

PHP does not interact with front-end, call a JavaScript function so it will never work:

function continuar_produtos()
{
<?php
//Codigo PHP aqui
?>
}

PHP has already been executed before the page is rendered on your screen, when running continuar_produtos it will not run PHP again, it will only call something that has already been processed, meaning it is meaningless.

In any website, web project uses HTTP, there is no other means of communication, it is requisition = > server = > processes PHP = > download = > render.

Almost every day I see questions about running PHP within JavaScript, this does not work, it will never work, it's not a problem with PHP, it's because this is Web and Web is HTTP and it only works like this, even if it was not HTTP it is still communication between the client computer with another computer, so it does not make sense to work in parallel.

More or less like this:

ThisisthebasicprincipleforthosewhowillworkwithWeb,ifyoudonotknowthis,thenyoudonotknowwhatiswebandwhatisdoing,summarizingisnotacriticism,butapieceofadvice,learnthebasicsofHTTP,seesamplequestions:

What is the solution?

First understand how communication works between two machines and in case the web learns the basics of HTTP, the links I indicated already help a little and second is to use Ajax or change the approach of your code, in case if you will be using Ajax you will have to create a separate script to execute this process.

    
02.10.2017 / 18:05
2

Comments in the code itself.

 //declaração do array
 $listStr = Array();

 while($row = $result->fetch_assoc())
 {
   $id = $row['id'];
   $nome = $row['nome'];
   $tipo = $row['tipo'];
   $imagem = $row['imagem'];
   $modelo = $row['modelo'];
   // o array
   $listStr[] = $row["Name"];

 }


//repete o alert para cada elemento do array
foreach ($listStr as $val) {

   echo "<script>

   alert(\"$val\");

   </script>";

}
    
02.10.2017 / 17:09
0
<script>
    function jsLoad( ) 
    {
        $("#preload").hide();
            continuar_produtos();
    }
    function continuar_produtos()
    {
        <?php $nome = '';?>
        <?php
            //1. Dados de conex?o
            $host = "localhost";
            $bd = "bancodedadosr";
            $usr = "root";
            $psw = "12345";

            //3. Cria a conex?o
            $conn = new mysqli($host, $usr, $psw, $bd);
            if ($conn->connect_error) 
            {
                die("A conex?o falhou, consulte o suporte: " . $conn->connect_error);
            } 
            //4. D? um SELECT no Banco de Dados utilizando os dados recebidos via POST
            $sql = "SELECT id, nome, tipo, imagem, modelo FROM produtos";
            $result = $conn->query($sql);
            //5. D? um while e armazena na vari?vel o valor dos dados
            if ($result->num_rows > 0)
            {

                 while($row = $result->fetch_assoc())
                 {
                   //6.5. Criar n? filho (resultado)
                   $id = $row['id'];
                   $nome = $row['nome'];
                   $tipo = $row['tipo'];
                   $imagem = $row['imagem'];
                   print("<SCRIPT language=javascript>alert('".$nome."');</SCRIPT>");
                }
            }    
        ?>

        //alert(<?php print_r($nome); ?>);
    }
    function jsDivStore()
    {
        $("#store").show();

        $( "#store" ).load( "new-product.php", function() {

        });

    }
</script>

I'm not sure if that's what you're talking about.

    
02.10.2017 / 15:58