-3

I am trying to pass JS variable to php echo statement.

here is my code

<?php print '<a href="thisTest.html?id=my_JS_value">test</a>'; ?>

how can I do that

I just test this and it works but how can I write the value within the href

alert(myvalue); ";

Man Mann
  • 423
  • 2
  • 10
  • 17
  • 1
    How are you calling php? You are showing no JS. Right now you are printing out a piece of text... – Floris Jul 31 '13 at 22:49

4 Answers4

4

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:

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

Then, implement DoNav accordingly:

function DoNav(url)
{
   location.href = url + '?id=' + my_JS_value; // Navigate to the new URL with the JavaScript variable
}
Mike Christensen
  • 88,082
  • 50
  • 208
  • 326
  • but I am using this echo after page load – Man Mann Jul 31 '13 at 22:50
  • I think that JS would have to trigger the load of another page, and pass the value of the variable through a _GET or _POST ... – Floris Jul 31 '13 at 22:50
  • @ManMann - Then you need to implement a way to pass that JavaScript variable back up to the server. This is usually done via AJAX, or a URL parameter, or hidden form field. – Mike Christensen Jul 31 '13 at 22:53
1

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.

caw
  • 30,999
  • 61
  • 181
  • 291
0

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>');
Ferdinand Torggler
  • 1,304
  • 10
  • 11
0

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.

<?php 
print '<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

ffflabs
  • 17,166
  • 5
  • 51
  • 77