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?
-
I have the same problem as you. Have you solved it ?SUN Jiangong– SUN Jiangong2009年12月21日 14:37:42 +00:00Commented Dec 21, 2009 at 14:37
-
Such a GREAT question ,seriously! Thanks for postingYusha– Yusha2016年11月12日 23:52:14 +00:00Commented Nov 12, 2016 at 23:52
5 Answers 5
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'];
?>
2 Comments
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.
Comments
If you don't have experience with or need Ajax, then just stuff your data into a post/get, and send the data back to your page.
Comments
You would have to use Ajax as a client-side script cannot be invoked by server-side code with the results available on server side scope. You could have to make an Ajax call on the client side which will set the PHP variable.
Comments
<script>
function get_Data(){
var name;
var job;
.....
return buffer;
}
function getData()
{
var agree=confirm("get data?");
if (agree)
{
document.getElementById('javascriptOutPut').value = get_Data();
return true;
}
else
{
return false;
}
}
</script>
<form method="post" action="" onsubmit="return getData()"/>
<input type="submit" name="save" />
<input type="hidden" name="javascriptOutPut" id="javascriptOutPut"/>
</form>
<?php
if(isset($_POST['save']))
{
var_dump($_POST['javascriptOutPut']);
}
?>