I have some question about concatenation php string to javascript string ...
for example:
php variable
$man = "Jamse";
and have javascript function
<script>
if (document.getElementById("fname").value == "") {
q = false;
msg = <?php echo 'Please fill first name'.$formErrors['fname'].'\n' ?>;
}
</script>
i want to do something like this can anyone help me ?
4 Answers 4
alert('my name is: <?php echo $man; ?>' );
7 Comments
<?php echo $man; ?> will be replaced with whatever is in $man; in this case the rendered output will be alert('my name is: Jamse' );$man is populated via user input (via form, etc.) you will want to validate your input.$formErrors is declared and has valid values.<?php echo 'Please fill first name '.$formErrors['fname'].'\n' ?>;alert('my name is: <?= $man; ?>');
Since PHP will insert $man on the server side, it's not a separate string that must be combined by JS. All the browser will see is
alert('my name is: Jamse');
Comments
Why not write it all in php?
<?php
$man = "Jamse";
echo "<script>
function alertMyName() {
alert('my name is:" . $man . "');
}
</script>";
?>
2 Comments
The other answers are true, I just forgot to write quotes and javascript did not understand it was a String and gave me an error. The correct code:
if (document.getElementById("fname").value == "") {
q = false;
msg = "<?php echo 'Please fill first name'.$formErrors['fname'].'\n'; ?>";
}
2 Comments
Explore related questions
See similar questions with these tags.