Assigning Js Value To Php
Solution 1:
When working between JavaScript and php you must remember one is client side (JavaScript) and the other server side (php). Therefore php can insert values into javascript before it is sent to the client and then rendered (processed). Although the reverse cannot happen as the "scope" of JavaScript is on the clients computer.
The way around this is to use AJAX requests from the client back to the server sending back the data / variable values you need.
JQuery provides an easy to use library with AJAX functionality.
Please see http://api.jquery.com/jQuery.ajax/
Solution 2:
PHP is server-side, JS is client side. This means the PHP will run far before the JS ever gets assigned. The only way a PHP file is going to get a JS variable is if you post it using Ajax
Solution 3:
One option would be to dynamically load the PHP-generated script and pass some GET
parameters to the PHP. This would still require ajax, but could be done cleanly with jQuery. If you go with jQuery, this is the documentation for getScript
.
EDIT
So, your HTML file should look like this:
<!-- your first javascript file --><scripttype="text/javascript"src="load.js"></script><!-- load jQuery library --><scripttype="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><scripttype="text/javascript>
// get the variable from your first javascript file
// via a getter function or global variable
var x = getVarFromFirstFile();
// this will load your second 'javascript' (generated by php) file
// and will pass the variable 'x' as a GET parameter to the php
$.getScript("load2.php?x="+x);
</script>
Then the php in load2.php could access the variable x (originally from load.js) like this:
<?php$x = $_GET['x'];
...
Post a Comment for "Assigning Js Value To Php"