0

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

6

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

Sign up to request clarification or add additional context in comments.

7 Comments

what can i do if i need to exactly concat it ?
When your page is rendeded, <?php echo $man; ?> will be replaced with whatever is in $man; in this case the rendered output will be alert('my name is: Jamse' );
@MikeChristensen That is a good point. If $man is populated via user input (via form, etc.) you will want to validate your input.
The question as you have it now should work, assuming $formErrors is declared and has valid values.
Just an aside, you may want to put in a space :) <?php echo 'Please fill first name '.$formErrors['fname'].'\n' ?>;
|
1
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

1

Why not write it all in php?

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

2 Comments

@ElGavilan can you elaborate?
It is better to leave the static parts of the HTML and javascript code in place and only use PHP to render the dynamic parts. Echoing the entire HTML is generally considered bad form as it makes your code harder to maintain and more prone to errors.
0

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

Are you answering your own question? Or posting further info? It's hard to understand the sentence above the code (plus the sentence is part of the code block). If this is indeed an answer, please edit it to be readable. If it's additional info for your question, edit your question.
@DavidMakogon I think he's just agreeing with the other answers, which told him to use quotes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.