I have the following code in JavaScript:
PHP Code:-
If this is related to a form submission, use a hidden inputinside the form and change the hidden input value to this variable value. Then you can get that hidden input value in the php page and assign it to your php variable after form submission.
Update:
According to your edit, it seems you don't understand how javascript and php works. Javascript is a client side language, and php is a serverside language. Therefore you cannot execute javascript logic and use that variable value to a php variable when you execute relevant page in the server. You can run the relevant javascript logic after client browser process the web page returned from the web server (which has already executed the php code for the relevant page). After the execution of the javascript code and after assigning the relevant value to the relevant javascript variable, you can use form submission or ajax to send that javascript variable value to use by another php page (or a request to process and get the same php page).
JavaScript variable = PHP variable try follow:-
<script>
var a="Hello";
<?php
$variable='a';
?>
</script>
Note:-It run only when you do php code under script tag.I have a successfully initialise php variable.
<html>
<head>
<script>
var a="Hello";
</script>
</head>
<body>
<?php
echo $variable = "<script>document.write(a)</script>"; //I want above javascript variable 'a' value to be store here
?>
</body>
in your view:
<?php $value = '<p id="course_id"></p>';?>
javascript code:
var course = document.getElementById("courses").value;
document.getElementById("course_id").innerHTML = course;
You really can't. PHP is generated at the server then sent to the browser, where JS starts to do it's stuff. So, whatever happens in JS on a page, PHP doesn't know because it's already done it's stuff. @manjula is correct, that if you want that to happen, you'd have to use a POST, or an ajax.
The ideal method would be to pass it with an AJAX call, but for a quick and dirty method, all you'd have to do is reload the page with this variable in a $_GET
parameter -
<script>
var a="Hello";
window.location.href = window.location.href+'?a='+a;
</script>
Your page will reload and now in your PHP, you'll have access to the $_GET['a']
variable.
<?php
$variable = $_GET['a'];
?>