Rio Eduardo
Rio Eduardo

Reputation: 137

How to use data created by JS in PHP?

This is my code

<script type="text/javascript">
function countNumber(){
  var number = 10;
  document.getElementById("n").innerHTML=number;
}
</script>
<body onload="countNumber()">
<?php
$a = "?"; //<-- here i want to get the innerHtml of the "n"-id-element
echo $a+1;
?>
</body>

How do I access the HTML-data at the initialization of $a?

Upvotes: 1

Views: 80

Answers (3)

Simon Thornett
Simon Thornett

Reputation: 56

Not sure if this helps but you can echo a php variable into the script you call onload like this:

<script type="text/javascript">
function countNumber(new_num){
var number = 10 + new_num;
document.getElementById("n").innerHTML=number;
}
</script>
<body onload="countNumber(<?php echo 1; ?>)">
<?php
$a = "<div id='n'></div>";
echo $a;
?>
</body>

Where

<?php echo 1; ?>

1 the number you want to run in the script.

Upvotes: 0

lt.kraken
lt.kraken

Reputation: 1300

The best is to work from client-server-client. Which would result in something similar like:

PHP (calc.php):

$number = 3;
echo $number;

JS:

$.get('calc.php', function (data) {
    var responseNumber = parseInt(data, 10);
    alert(3 + responseNumber);
});

ofcourse you could call PHP in your JS, but the you'd have to make sure the number would exist..

$("#divId").html("<?=$phpNumber;?>");

Upvotes: 0

LionC
LionC

Reputation: 3106

You cannot access the data the way you want, as PHP runs on the server, then the files are transfered to the client and then the Javascript runs on the client. If you really need to process data that was calculated with Javascript, you need AJAX or forms.

Upvotes: 2

Related Questions