Unable to pass argument to javascript function, which is a PHP script variable

I am new to php, I have no good idea how to do things between php and javascript, please correct me. If I am 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 need to raise an onclick event for an image tag through javascript. The img tag is created using php script and I want it to be like

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

I tried this way

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

Please help me with them. is it really possible? Since I know that javascript is a script for the browser, and php is server-side scripts, and can we pass variables from php to javascript this way?

+4
source share
5 answers

Funny, everyone who has answered so far has changed the printf parameter to use double quotes or to combine a variable. Why not:

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

since it already uses printf () ...?

Also, you really don't need the value of PHP, as it is already in HTML. You can simply use:

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

try it

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

You have a problem with a quote .

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

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

You need to print the double-quoted string to use the variable reference:

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

I have not tested it, but this should work for you.

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

All Articles