2

I have a page 1.php and the code goes here(just a clone)

<?php
include '2.php'
?>
<script>
function rename(){
var x='renamedvalue';
}
</script>
<input type="button" onclick="return rename();">

And the page 2.php

<script>
var x ='somevalue';
</script>

I have to change the value of this variable onclick button event on page1.

Ganesh Bora
  • 1,133
  • 9
  • 17
lakshya_arora
  • 791
  • 5
  • 18

4 Answers4

3

Since you're including 2.php into 1.php, you'll end up having a single page. You could create a global Javascript value, like you already did in 2.php, like this:

<script>
var x ='somevalue';
</script>

Your problem in 1.php lies here:

var x='renamedvalue';

With this snippet, you are redefining a variable named x inside your rename function. To use the global variable x, change the line above to exclude the "var" (which redeclares another local value "x" inside rename()):

x='renamedvalue';
Filippos Karapetis
  • 4,367
  • 21
  • 39
1

If you want to pass variables between JS and PHP its probably easier to use forms:

<script>
function rename(){
    var x='renamedvalue';
    document.getElementById("x").value = x;
}
</script>
<form action="2.php" method="post">
<input type="hidden" value="" id="x" name="x">
<input type="button" onclick="return rename();">
</form>

page2.php

<script>
var x ='<?php print $_POST["x"] ?>';
</script>

You will need to perform some input cleaning but you get the idea

Bloafer
  • 1,324
  • 7
  • 12
  • If you wanted to keep the variables on the same page you could use an Ajax method of passing the vars, but it would work in a similar way – Bloafer Jun 06 '13 at 08:10
0

defining variable outside the js function make it global and allow to change thee value on onclick event.

<?php
include '2.php'
?>
<script>
var x = ''; //global variable
function rename(){
x='renamedvalue';
}
</script>
<input type="button" onclick="return rename();">
Ganesh Bora
  • 1,133
  • 9
  • 17
0

you must use the global variable x

write x='renamedvalue' instead of var x='renamedvalue'

Mohammad Masoudian
  • 3,483
  • 7
  • 27
  • 45