VostanAzatyan
VostanAzatyan

Reputation: 647

Concatenation php string to javascript string

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 ?

Upvotes: 0

Views: 4740

Answers (4)

VostanAzatyan
VostanAzatyan

Reputation: 647

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'; ?>";
    }

Upvotes: 0

user3147515
user3147515

Reputation: 59

Why not write it all in php?

<?php
$man = "Jamse";
echo "<script>
function alertMyName() {
    alert('my name is:" . $man . "');
}
</script>";
?>

Upvotes: 1

Mooseman
Mooseman

Reputation: 18891

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');

Upvotes: 1

ElGavilan
ElGavilan

Reputation: 6894

alert('my name is: <?php echo $man; ?>' );

Upvotes: 6

Related Questions