String PHP in Alert Javascript

Asked

Viewed 3,022 times

1

How can I take the return of a PHP database and play the result in a alert javascript ?

while($row = mysql_fetch_array( $result )) {
 // Print out the contents of each row into a table
 $nome = $row['Nome'];
 echo "<tr><td>"; 
 echo $row['id'];
 echo "</td><td>"; 
 echo $nome;
 echo "</td></tr>"; 

 echo '<script language="javascript">';
 echo 'alert("message successfully sent")'; <------- INSERIR A VARIÁVEL ( $Nome ) AQUI DENTRO
 echo '</script>';

}
  • 1

    echo 'alert("message successfully sent '.$Nome.'")' or sprintf('alert("message successfully sent %s")', $Nome)

1 answer

2


Just concatenate, like this:

 echo 'alert("message successfully sent '.$nome.'");';

Just be careful with reserved Javascript character conflicts. Example, if the string comes from PHP has double quote (double quote), it will act as an XSS injection

Example of conflict:

$nome = 'nome "com aspa"';
echo 'alert("message successfully sent '.$nome.'");';

will result in alert("message successfully sent nome "com aspa"");, causing Javascript syntax error.

To give consistency to the code, pass the php string inside the function addslashes()

$nome = 'nome "com aspa"';
echo 'alert("message successfully sent '.addslashes($nome).'");';

Will return alert("message successfully sent nome \"com aspa\"");

As the quotes are escaped, the syntax error in Javascript is avoided.

  • How cool is it that if Alert java script was outside <?php ? >, it would be possible to insert a PHP variable ? You can make a global variable in PHP ?

  • Then it would be enough to do so: alert("message successfully sent <?php echo $nome;?>");

Browser other questions tagged

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