Writing Javascript With Php
I am trying to right some some JavaScript to define a variable using PHP. The variable has a little jQuery in it which should get rendered by the client. I say 'should' but reall
Solution 1:
You have this:
<inputtype="hidden"id="id" value="123" />
So I can assume that you are getting that id from a db right? Maybe like this:
<inputtype="hidden"id="id"value="<?phpecho$row[id];?>" />
If this is the case do the following (I tested and works):
You don't need hidden inputs to do it.
<!DOCTYPE htmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><htmlxmlns="http://www.w3.org/1999/xhtml"><head><metahttp-equiv="content-type"content="text/html; charset=ISO-8859-1" /><title></title><scriptsrc="http://code.jquery.com/jquery-latest.js"type="text/javascript"></script><script>
$(function() {
<?php//From your SQL query you obtained//$row['id'] = 123;$id = $row['id'];
?>var o1={"foo":{"bar": "abc/index.php?=" + <?phpecho$id?>}};
console.log(o1);
<?php$d='abc/index.php';
$json='{"foo":{"bar": "'.$d.'?='.$id.'"}}';
//echo($json);$json=json_decode($json);
//echo(print_r($json,1));$json=json_encode($json);
//echo($json);echo("var o2=".$json.';');
?>console.log(o2);
});
</script></head><body></body></html>
Solution 2:
Untested, may contain errors:
<script>
$(function() {
var o1={"foo":{"bar": "abc/index.php?="+$("#id").val()}};
console.log(o1);
<?php$d='abc/index.php';
$json='{"foo":{"bar": "' . $d . '?="+$("#id").val()}}';
echo("var o2=".$json.';');
?>console.log(o2);
});
</script>
Solution 3:
I prefer make json with the json_encode, to avoid unexpected problems with parse and validation of json.
the json_encode and json_decode only work with UTF-8, another charset will result in a blank string, if it has special chars.
<script><?php$d = "abc/index.php";
$json['foo']['bar'] = $d . '?id=$("#id").val()';
echo"var o2 = ".json_encode($json);
?>console.log(o2);
</script>
Post a Comment for "Writing Javascript With Php"