3
votes

I have a Perl script which prints out of html page. I want to use javascript to pop alert msg. The alert message is defined as string in the perl variable. I am trying to pass the perl variable value to javascript function as argument but it's not working. Please help.

$perl_variable = "Welcome"; # alert msg

print <<START

<HTML>

some html code....

<p>Click the button to wait 3 seconds, then alert "Hello".</p>

<button onclick="myFunction('$perl_variable')">Try it</button>

<script>

function myFunction(var message){

setTimeout(function(){alert(message)},3000);

}

</script>

</HTML>

START
1
Did you mean perl_variable instead of path_qa_image? Look in your browser's error console; there is likely an error caused by not quoting the variable. - Matt Ball
Correcting comment - The path of file is defined in the perl variable to alert message - Kevin
I've edited your question to remove the reference to PERL; perl is not an acronym. - Quentin
While in this case it is fairly easy to see what is wrong, as a rule of thumb, when you are generating one programming language from another and the final result doesn't work - then first determine if the problem is that you don't know how to generate the code you want (in which case show the two sets of code) or if you don't know what code you should be generating (in which case show only the generated result and describe how its behaviour differs from what you expect). - Quentin

1 Answers

6
votes

NB: The first half of this answer refers to the code that originally (before edits) appeared in the question.

You need to:

  1. Use the right variable name
  2. Generate a JavaScript string literal (by quoting the data)

Such:

myFunction('$perl_variable')

Note that if your data might include characters that are not allowed in a JavaScript string literal (such as a new line), characters that have special meaning in a string literal (such as the quote mark that delimits it) or characters that have special meaning in HTML (such as the quote mark that delimits the attribute value) then you will also need to perform suitable escaping (in two steps, first for JS, then for HTML).


As an aside, your function definition in JS is also wrong:

function myFunction(var path){

The var keyword may not be used in the FormalParameterList. That should read:

function myFunction(path){