I am using PHP and JavaScript. My JavaScript code contains a function, get_data():
function get_Data(){
var name;
var job;
.....
return buffer;
}
Now I have PHP code with the following.
<?php
$i=0;
$buffer_data;
/* Here I need to get the value from JavaScript get_data() of buffer;
and assign to variable $buffer_data. */
?>
How do I assign the JavaScript function data into the PHP variable?
We can pass data from PHP to JavaScript in two ways depending on the situation. First, we can pass the data using the simple assignment operator if we want to perform the operation on the same page. Else we can pass data from PHP to JavaScript using Cookies.
You can execute Javascript through PHP by calling javascript code/function as a string in PHP and send it to the client browser to execute.
Besides, PHP and JavaScript similarities, these two languages are a powerful combination when used together. Large numbers of websites combine PHP and JavaScript – JavaScript for front-end and PHP for back-end as they offer much community support, various libraries, as well as a vast codebase of frameworks.
Javascript will be interpreted in Client's browser and you can not assign it to PHP variable which is interpreted on SERVER .
Use jQuery to send a JavaScript variable to your PHP file:
$url = 'path/to/phpFile.php';
$.get($url, {name: get_name(), job: get_job()});
In your PHP code, get your variables from $_GET['name']
and $_GET['job']
like this:
<?php
$buffer_data['name'] = $_GET['name'];
$buffer_data['job'] = $_GET['job'];
?>
JavaScript code is executed clientside while PHP is executed serverside, so you'll have to send the JavaScript values to the server. This could possibly be tucked in $_POST
or through Ajax.
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