Possible Duplicate:
javascript variable into php
Okay lets imagine I've a javascript variable "x"
<script>
var x="jsvar";
</script>
Now I want its value in php variable $y <?php $y; ?> How to do it.
Okay few people are confused i wanted to know is it possible if yes then how ?? if this isn't possible then comment here i'll remove it.
asked Oct 12, 2011 at 16:51
Mohit Bumb
2,4935 gold badges33 silver badges54 bronze badges
-
1in PHP how? are you passing it to PHP?zzzzBov– zzzzBov2011年10月12日 16:52:49 +00:00Commented Oct 12, 2011 at 16:52
-
3That variable exists in the browser, a php variable exists on the server, two very separate places. can you please elaborate on what your use is and we can suggest a method? The first thing that comes to mind is to submit a form that sends that value to the server, but, again, it depends on what you wantLandon– Landon2011年10月12日 16:53:56 +00:00Commented Oct 12, 2011 at 16:53
-
your options are ajax, POST, GET, href which one you wantMelsi– Melsi2011年10月12日 16:57:22 +00:00Commented Oct 12, 2011 at 16:57
-
3Someone needs to understand, that when javascript ir executed, the server has done it's job - there is no way to get back to it [PHP] in the current request. You have to make another request, perhaps, via ajax.Mārtiņš Briedis– Mārtiņš Briedis2011年10月12日 16:57:31 +00:00Commented Oct 12, 2011 at 16:57
-
@Briedis Thanks got my answer.Mohit Bumb– Mohit Bumb2011年10月12日 17:00:15 +00:00Commented Oct 12, 2011 at 17:00
1 Answer 1
You have to pass it to your PHP script, either via AJAX or via a formular with a submit button.
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){}; // change
xhr.open("POST", "your-script.php");
xhr.send("x="+x);
And the PHP script can look like this:
<?php
$y = isset($_POST['x']) ? $_POST['x'] : '';
echo $y;
?>
answered Oct 12, 2011 at 16:56
ComFreek
29.5k18 gold badges107 silver badges157 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
Mohit Bumb
is it possible with simple javascript or not ??
ComFreek
Yes! Look at the first code - this is (simple) JavaScript.
Mohit Bumb
ok can i ask one more question sorry i'm php developer but really bad in js what XMLHttpRequest(); can do ???
ComFreek
You can send requests to other scripts and servers with that object. This is also called AJAX (Asynchronous JavaScript And XML). Here are probably more information: developer.mozilla.org/En/XMLHttpRequest/Using_XMLHttpRequest
Mohit Bumb
okay thanks dude my mind is too much clear than before now with js thanks for help thumbs up
default