Skip to content Skip to sidebar Skip to footer

Pass Js Variable To Php Echo Statement

I am trying to pass JS variable to php echo statement. here is my code test'; ?> how can I do that I just

Solution 1:

This is impossible from a temporal point of view.

When the PHP code is run, there is no JavaScript. The page is not yet loaded into the browser. There is no JavaScript engine being run. There are no JavaScript variables. By the time the browser renders the page, the server code has already done its job.

With that said, you can render HTML which refers to a JavaScript function. For example:

<?phpprint'<a href="javascript:DoNav(\'thisTest.html\');">test</a>'; ?>

Then, implement DoNav accordingly:

functionDoNav(url)
{
   location.href = url + '?id=' + my_JS_value; // Navigate to the new URL with the JavaScript variable
}

Solution 2:

JavaScript and PHP cannot directly communicate as JavaScript is client-side and PHP is server-side, i.e. PHP is executed before the JavaScript is sent to the browser.

The only way to achieve what you want is to sent a request from JavaScript that calls a PHP script (e.g. AJAX) and passes the variable via GET (like your example) or POST.

Solution 3:

Javascript code is executed on the client side, so you do not have access to it. You can just create the link using Javascript, like this:

var my_JS_value = 0;
document.write('<a href="thisTest.html?id=' + my_JS_value+ '\">test</a>');

Solution 4:

You can insert the element with php and set the href attribute later with JS. Anyway there's a ton of other ways to achieve the same.

<?phpprint'<a id="mylinkelement" >test</a>
<script>
var mylinkelement=getElementById("mylinkelement");
mylinkelement.href="thisTest.html?id="+my_JS_value;
</script>'; 
?>

You don't even need php for that :D

Post a Comment for "Pass Js Variable To Php Echo Statement"