0

I have a php function which generates a javascript alert popup.

This function accepts a parameter message. My problem is that if message is a multiple line string, javascript won't alert the text because of the lack of '+' every line. How can I solve that?

function alert($msg) {
    echo '<script type="text/javascript">alert("'.$msg.'")</script>';
}

/* DOESN'T WORK */
  $msg = 'testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttest.
      testtesttesttesttesttesttesttest.
      testtesttesttesttesttesttesttesttesttest.';
  alert($msg);

/* WORKS */
  $msg = 'testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttest. testtesttesttesttesttest. testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttestttesttesttesttesttesttest.';
  alert($msg);
2
  • Why -1? Isn't this a serious question?!? @Pilot can you explain me why /? Commented Feb 24, 2014 at 13:37
  • Possible duplicate: stackoverflow.com/questions/805107/… Commented Feb 24, 2014 at 13:40

2 Answers 2

2

The problem is multiline strings in javascript need to be split with a \ at the end of each line.

function alert($msg) {
    echo '<script type="text/javascript">alert("'.$msg.'")</script>';
}

$msg = 'testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttest.\
      testtesttesttesttesttesttesttest.\
      testtesttesttesttesttesttesttesttesttest.';
alert($msg);
Sign up to request clarification or add additional context in comments.

Comments

0

Please user json_encode function in pass function parameter
json_code function is change link break into \n

<?php 
 function alert($msg) {
    echo '<script type="text/javascript">alert('.$msg.')</script>';
}

/* DOESN'T WORK */
  $msg = 'testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttest.
      testtesttesttesttesttesttesttest.
      testtesttesttesttesttesttesttesttesttest.';
  alert(json_encode($msg));
 ?>

This chrome enter image description here

5 Comments

This won't work. The problem is the multiline string, not the function parameter.
@jamesj, json_encode function will add \r\n of line break so it will work
But the line above there isn't valid javascript. Try pasting it into the chrome dev console. It gives me SyntaxError: Unexpected token ILLEGAL
@jamesj please see attachment image, i used same code
Executing it as a php script first though. Nowhere does the question mention PHP (although I now notice that is what OP was using).

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.