Javascript beginner - Pass argument to javascript

Asked

Viewed 57 times

1

<a onclick="onclick_edit(<?php echo 'aaa';?>);">

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

The Javascript function is not even called, only works if I try to pass PHP number. If I try to pass string PHP does not work. It works string only in hand, no exit use PHP.

1 answer

3

When you do

onclick="onclick_edit(<?php echo 'aaa';?>);"

The result will be HTML

onclick="onclick_edit(aaa);"

You can confirm this by viewing the source code of your page. When trying to run, Javascript will try to pass the variable aaa to the function, giving variable error not defined (you can check in the console that).

In order to be able to do what you want, you need to display the value with quotes, so that Javascript understands how string:

onclick="onclick_edit(<?php echo "'aaa'";?>);"

So the result will be

onclick="onclick_edit('aaa');"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.