Passing Parameters To Javascript Using Php
Solution 1:
You need quotes for both the php side and the Javascript side. You've only got php quotes there.
<ahref="javascript:;"onClick="tweeet('<?phpecho'myid'; ?>')">My Tweets!</a>
looks weird but it should work, though I'm no php expert. Note that if there's any chance that "myid" (on the php side) might contain user-supplied data (like, something that came from an <input>
field at some time), or if it's otherwise unpredictable, then it has to be put through something on the server side to make sure that the resulting tag is "clean".
Solution 2:
I usually do as following:
<script>var jsvar = <?=json_encode($php_var)?>;
</script>
After that I can use jsvar
under the javascript codes. And for readability I usually place all those assignments in an own script tag.
What you gain by using <?=json_encode($php_var)?>
is that you won't need to go on escaping, and it works for arrays and hashes as well as strings, numbers etc...
For example, following php code:
<?php$php_string = "hello";
$php_array = array( 'a', 'b', 'c' );
$php_hash = array( 'a' => 1, 'b' => 16, 'c' => 42 );
$php_number = 123;
$php_bool = false;
$php_null = null;
?><scripttype="text/javascript">var js_string = <?=json_encode($php_string)?>;
var js_array = <?=json_encode($php_array)?>;
var js_hash = <?=json_encode($php_hash)?>;
var js_number = <?=json_encode($php_number)?>;
var js_bool = <?=json_encode($php_bool)?>;
var js_null = <?=json_encode($php_null)?>;
</script>
produces the following result:
<scripttype="text/javascript">var js_string = "hello";
var js_array = ["a","b","c"];
var js_hash = {"a":1,"b":16,"c":42};
var js_number = 123;
var js_bool = false;
var js_null = null;
</script>
Solution 3:
You forgot to Quote your answer. You are echoing the string OK, but you need to ' ' the response so JavaScript will know it's a string. You can use ' or \"
Solution 4:
<ahref="javascript:;"onClick="tweeet('<?='myid'; ?>')">My Tweets!</a>
Uses short echo thing.
Post a Comment for "Passing Parameters To Javascript Using Php"