First I thought that I had to convert JavaScript to PHP, but then I found out that I cannot because of server and client side executions. So now I simply want to send ONE variable
<script type="text/javascript"> function scriptvariable() { var theContents = "the variable"; } </script>
to a PHP variable
<?php $phpvariable ?>
That function in the JavaScript executes when let's say I click on a button.
Now I have no idea on how to assign that phpvariable to the JavaScript one to use the phpvariable to look up stuff in my database. I know I can add it to my url or some thing and refresh the page, but I would like to do it with AJAX as I might have to use this Ajax method further in my webpage.
So is there an easy way to do this without having to dump pages of code on my page to do one simple thing?
The way to pass a JavaScript variable to PHP is through a request. This type of URL is only visible if we use the GET action, the POST action hides the information in the URL. Server Side(PHP): On the server side PHP page, we request for the data submitted by the form and display the result. $result = $_GET [ 'data' ];
You can easily get the JavaScript variable value on the same page in PHP. Try the following codeL. <script> var res = "success"; </script> <? php echo "<script>document.
1) First add a cookie jquery plugin. 2) Then store that window width in a cookie variable. 3) Access your cookie in PHP like $_COOKIE['variable name'].
PHP runs on the server and Javascript runs on the client, so you can't set a PHP variable to equal a Javascript variable without sending the value to the server. You can, however, set a Javascript variable to equal a PHP variable:
<script type="text/javascript"> var foo = '<?php echo $foo ?>'; </script>
To send a Javascript value to PHP you'd need to use AJAX. With jQuery, it would look something like this (most basic example possible):
var variableToSend = 'foo'; $.post('file.php', {variable: variableToSend});
On your server, you would need to receive the variable sent in the post:
$variable = $_POST['variable'];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With