Sate Wedos
Sate Wedos

Reputation: 589

Can I create JavaScript function in PHP looping

I want to make an alert using JavaScript. This is an example I have made bls.hol.es. When I click first name will display an alert containing the first name. But it displays an alert containing the second name. This is my code:

<?php
$arrayname=array('iqbal', 'rezza');
$arrayaddress=array('teloyo', 'karang rejo');
for ($x = 0; $x <= 1; $x++)
{
    $name=$arrayname[$x]; 
    $address=$arrayaddress[$x];   // indent consistently!!
?>

<script>
    function call()
    {
        var nik = "<?php echo $name ?>";    // semicolons not needed in the embedded PHP code
        var addres = "<?php echo $address ?>";   // indent consistently!!
        alert(nik+address);
    }
</script>

<a href="javascript:call();"><?php echo $name ?></a>

<?php
} ?>

Whether this can be done my way?

What is wrong in my code?

Upvotes: 1

Views: 65

Answers (3)

mickmackusa
mickmackusa

Reputation: 47904

Just loop the html with inline onclick using the php loop.

<a onclick="alert(this.innerHTML);">iqbal</a>
<a onclick="alert(this.innerHTML);">rezza</a>

Here's the php:

$arrayname=array('iqbal', 'rezza');
foreach($arrayname as $v){
    echo "<a onclick='alert(this.innerHTML);'>$v</a>";
    // or echo "<a onclick='alert($v);'>$v</a>";
}

The bottom line is, you don't want to write duplicate functions. Write one function, call it as many times as you wish, and pass $v as a parameter to it, then you can do what ever you wish with the parameter inside the function.

If you are making a function call and want to send three variables at time, you can set it up like this in php:

<script>
function call(one,two,three){
    alert(one);
    alert(two);
    alert(three);
}
</script>
<?php
$array=[
    ['a','b','c'],
    ['d','e','f']
];

foreach($array as $a){
    echo "<a href=\"javascript:call('{$a[0]}','{$a[1]}','{$a[2]}');\">{$a[0]} and {$a[1]} and {$a[2]}</a>";
}

Upvotes: 1

FKEinternet
FKEinternet

Reputation: 1060

What's wrong with your code is the second pass through the loop redefines the call() function with the second name, so by the time it's been rendered in the browser window, only the second instance of the function is available to run.

Upvotes: 1

Jan Rydrych
Jan Rydrych

Reputation: 2258

That happens because you're creating js function call() inside the loop, so technically you have two declarations of call() in resulting code. When you call the call() function, then both of them are processed.

I assume you want to use more logic in the call() in the future, so the solution would be to alter your js code to process the name as a parameter nad move it outside the loop like:

 function call(name){
     alert(name);
 }

and alter the link:

<a href="javascript:call('<?php echo $name;?>');"><?php echo $name;?></a>

Upvotes: 2

Related Questions