PHP String in Alert Javascript

1

How can I get the return of a database in PHP and play the result in 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>';

}
    
asked by anonymous 04.03.2016 / 13:03

1 answer

2

Just concatenate, like this:

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

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

Conflict example:

$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 make the code consistent, pass the string php into the function addslashes ()

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

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

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

    
04.03.2016 / 13:23