Insert PHP into Javascript

Asked

Viewed 947 times

0

Hello

I need to get the results of a SELECT in PHP and display in a ALERT within a function in JAVASCRIPT, where when performing the function JAVASCRIPT wheel the PHP and the WHILE. How can I do it? 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() {

});

}

Resolved issue: Code working:

<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

  • Do you want to run while from PHP as if it were Javascript? There is no way to do this. PHP runs on the server and comes back as HTML.

  • You will have to use AJAX, make a request to a php page with javascript and return a Json to use.

  • I did it once, but I don’t remember how I did it and I didn’t use AJAX. I think I put ALERT in the middle of PHP’s WHILE and showed ALERT the SELECT results.

  • How to answer your own question: I can answer my own question?.

3 answers

3

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

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

PHP has already been run 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, ie has no sense.

On any site, web project uses HTTP, there is no other means of communication, it is request => server => processes PHP => download => render.

Almost every day I see questions about running PHP within Javascript, it doesn’t work, it never will, 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 wasn’t HTTP still is communication between the client’s computer with another computer, so it makes no sense to run parallel.

Sort of like this:

modelo HTTP cliente-servidor

This is the basic principle for those who will work with Web, if you do not know this, then you do not know what is web or what you are doing, in short it is not a criticism, but a piece of advice, learn the basics of HTTP, see examples of questions:

What is the solution?

First understand how the communication between two machines works and in the case of web learning 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 to use Ajax you will have to create a separate script to run this process.

  • The code I posted above is working, I mixed php with javascript and it worked.

2

Comments on 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>";

}
  • Very cool your code, but I’ve solved it. Thank you

  • Why the concatenation and explode ? It was not easier to have directly used an array with $listStr[] = $row["nome"]; and foreach($listStr as $val){ ?

  • You should have the array declaration before the while. Example what I’m trying to say.

  • It does not affect. In the example I put it works even with the 4.4.9. Just try it on

  • @Isac do not know where you are seeing that my script is different than you suggest. :)

  • That’s it, now it’s good!

  • @Isac was worth, living and learning

  • The code I posted is working, I mixed php and javascript and it worked.

Show 3 more comments

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 that’s what you’re talking about.

  • So, what I need is when I call the CONTINUAR_PRODUTOS function every SELECT result displays in ALERT in JAVASCRIPT. I tested this code but it didn’t work, which could be wrong ?

  • I edited my code in the While block added a print with Alert.

  • The code I posted is working, I mixed php and javascript and it worked.

Browser other questions tagged

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