Reputation: 133
Interesting. I have 2 links calling 2 JS functions - the first works , the second - doesn't. It only calls function addns() when the argument is empty. Otherwise nope...
PHP:
while ($row_mem = mysqli_fetch_array($mem)) {
$membs[] = $row_mem['username'];
$membs_id[] = $row_mem['user_id'];
}
}
//FIRST FOREACH CALL PROPERLY
foreach($membs_id as $val_id) {
echo"<a href='javascript:addms($val_id)'><img src='$pcheck' width='66' height='68'
border='1' class='currmem'/></a> ";
}
//THIS ONE DOESN'T
foreach($membs as $mes_id) {
echo"<a href='javascript:addns($mes_id)'>$mes_id</a> ";
}
JS:
function addms(msid) {
var addm = msid;
alert(addm);
}
function addns(nsid) {
var addn = nsid;
alert(addn);
}
I cannot see any error - thanks for comments !
Upvotes: 1
Views: 133
Reputation: 52
Update to match new answer:
you need to put quotes around your variables. ($val_id)
probably works because you're retrieving an id which I'm guessing is an integer, so it's a valid JavaScript literal.
($mes_id)
probably doesn't work because you're getting strings back but not wrapped with quotes, so they aren't valid JavaScript literals.
so usernames will be joe and shmoe, javascript becoems
addns(joe)
and addns(shmoe)
, which is probably not what you want. You want addns("joe")
and addns("shmoe")
.
Also note once you fix this is an XSS vulnerability if users can choose their username.
Upvotes: 3
Reputation: 10047
See here: https://www.php.net/manual/en/function.echo.php
Using single quotes will print the variable name, not the value
echo 'foo is $foo'; // foo is $foo
I can't see how you're using the wrong quotes to be honest, other than if the JavaScript function requires them, so just to make everything simple, try this:
//FIRST FOREACH CALL PROPERLY
foreach($membs_id as $val_id) {
echo "<a href='javascript:addms(\"".$val_id."\")'><img src='".$pcheck."' width='66' height='68'
border='1' class='currmem'/></a> ";
}
//THIS ONE DOESN'T
foreach($membs as $mes_id) {
echo "<a href='javascript:addns(\"".$mes_id."\")'>".$mes_id."</a> ";
}
Upvotes: 1