4

Im new to php, I dont have good idea how to make things between php and javascript please correct me If im wrong

<!doctype html>
<html>
<head>
<Script type="text/javascript">
function show(m)
{
 var k = document.getElementById(m);
 k.src="four.jpg";
}
</head>
<body>
<? --some php code--
  $i       = 2;
  $row[$i] = "somefilename";
  printf('<img src="%s" id="%d"  onclick="show($i)"/>', $row[$i],$i);
?>

This is my sample.php file.I wanted to raise a onclick event for the image tag through javascript,The img tag is created using php script and I want it to be like these

onclick="show($i)" should be made like below
onclick="show('2')" <!-- and here 2 is the value of php variable

I had tried these way

 onclick="show('$i')" but it passes $i as the parameter to javascript show() function 
 but not the value 2

Please help me with these. actually is it possible ? As i know javascript is a browser scripting and php is server side scripting and can we pass variables from php to javascript these way ?

niko
  • 9,285
  • 27
  • 84
  • 131

5 Answers5

2

try this

printf('<img src="%s" id="%d"  onclick="show('.$i.')"/>', $row[$i],$i);
2

You have quote problem.

In PHP, everything inside single quote is printed AS-IS. So, in your situation, it should be:

printf('<img src="%s" id="%d"  onclick="show(' . $i . ')"/>', $row[$i],$i);
ariefbayu
  • 21,849
  • 12
  • 71
  • 92
2

Funny, everybody who's answered so far has changed the printf parameter to either use double quotes or concatenate the variable. Why not:

printf('<img src="%s" id="%d"  onclick="show(%d)"/>', $row[$i],$i,$i);

as he is already using printf()...?

Furthermore, you don't actually need the value from PHP as it is already in the HTML. You can just use:

printf('<img src="%s" id="%d"  onclick="show(this.id)"/>', $row[$i],$i);
Nikoloff
  • 4,050
  • 1
  • 17
  • 19
1

You need to print the string with double quotes in order to use a variable reference:

printf("<img src=\"%s\" id=\"%d\"  onclick=\"show($i)\" />", $row[$i],$i);

I haven't tested it but that should work for you.

Jeff LaFay
  • 12,882
  • 13
  • 71
  • 101
0
<?php

  $i       = 2;
  $row[$i] = "somefilename";
  printf('<img src="%s" id="%d"  onclick="show(' . "'" . %d . "'" . ')"/>', $row[$i],$i);

?>
Tobias Golbs
  • 4,586
  • 3
  • 28
  • 49