Fynn
Fynn

Reputation: 210

Passing a variable to JavaScript function

I would like to call a JavaScript function from my php page, which looks like this:

xyz.php

for ($i = 0; $i < count($temp2a); $i++) {
    $URL = "xyz.php?eingabe=".$temp2a[$i]."&eingabe2=".$datei;
    echo '<p><a href="#" onClick="test("'.$URL.'")">link</a></p>';
}

<script src="java.js"></script>

java.js

function test(para){
    alert(para);
        alert("Para"); 
    }

Calling the function without a variable works. test() outputs two alerts:

Undefined
Para

Whenever I try to pass a variable, the function does not get called at all. No alert or anything else.

Upvotes: 0

Views: 51

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388406

You can do something like

echo '<p><a href="'.$temp2a[$i].'" onClick="test(\''.$URL.'\')">link</a></p>';

Upvotes: 1

Mihir Bhatt
Mihir Bhatt

Reputation: 3155

Blockquote Replace your code, It seems mistake of single quotes balance.

for ($i = 0; $i < count($temp2a); $i++) {
 $URL = "xyz.php?eingabe=".$temp2a[$i]."&eingabe2=".$datei;
 echo '<p><a href="'.$temp2a[$i].'" onClick="test(\"'.$URL.'\")">link</a>   
 </p>';
}

Upvotes: 0

Related Questions