gamal
gamal

Reputation: 1665

Set or change PHP variable in JavaScript

I am new to PHP and JavaScript.. I need to take the height of a div and assign it in to PHP variable so that I can use it later for further processes.

This is how tried it for now, but it did not workout well..

<div id="leftSideDataBox" style="height:auto; overflow:hidden">
// some web form contents 
</div>

<?php $leftSideDataBoxHight=0;?>
<script>
     var myDiv = document.getElementById("leftSideDataBox");
     var boxHight=myDiv.clientHeight;
     <?php $leftSideDataBoxHight?>=boxHight;
</script>
<?php if(leftSideDataBoxHight<100)
{
//do some window arrangements
}?>

I know it was not ROCKET SCIENCE, but i could not find any solution for it.

When I put a alert to it it displaces the height of the div

<script>
    var myDiv = document.getElementById("leftSideDataBox");
    alert(myDiv.clientHeight)
</script>

Do you guys have any solutions??? Thank You..

Upvotes: 3

Views: 65824

Answers (4)

Tarun Kumar
Tarun Kumar

Reputation: 11

Use $_GET and $_POST function to change value of php variable from url parameter.

Upvotes: 1

Rajon Kobir
Rajon Kobir

Reputation: 173

You can’t change the value of a PHP variable in JavaScript. PHP runs on the server and JS runs on the client PC. Using AJAX might be a better solution.

Upvotes: 5

Vasim Shaikh
Vasim Shaikh

Reputation: 4542

You cannot pass variable values from the current page javascript to the current page PHP code... PHP code runs at the server side and it doesn't know anything about what is going on on the client side.

You can use hidden field here.

HTML:

<div>
 // your div
</div>
<input type="hidden" id="hiddencontainer" name="hiddencontainer"/>

<script>
  var myhidden = document.getElementById("hiddencontainer");
  myhidden.value=boxHeight;
</script>

In PHP side you can get value using,

$boxsize=$_REQUEST["hiddencontainer"];
echo $boxsize;

Upvotes: 11

Jesper
Jesper

Reputation: 3834

Answer:

You simply cannot do that, you need to understand the difference between client/server side programming, you cannot assign Javascript value to PHP variable, yea but you can assign PHP value to your javascript

Reference:

How to assign php variable in JavaScript value assign?

Maybe Take a look at this too:

How to pass JavaScript variables to PHP?

Upvotes: 1

Related Questions