Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I need to pass js variavle to php part at this code:

<script type="text/javascript>
var x=32;
</script>
<?
echo $x;
?>

I want to use x value at php. How to do that?? is there any way without reloading the page?

share|improve this question

closed as not a real question by Enrico Pallazzo, kay, random, j0k, forsvarir Jul 16 '12 at 7:28

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, see the FAQ.

4 Answers

You can't do that.

PHP code has already finished processing by the time the page gets to the browser. It's too late for Javascript to affect it.

share|improve this answer

Actually you can not do this. PHP runs on server, JS runs on client machine.
One thing you can do is to use JS to send the URL back with a variable in it such as: http://www.site.com/index.php?uid=1
Something like:

window.location.href=”index.php?uid=1";

Then in PHP you can get it:

$somevar = $_GET["uid"];
share|improve this answer
You can also use AJAX, which essentially would do the same thing, but also gives you the option to use POST which allows you to past more data through. AJAX – Valjas Jul 15 '12 at 15:44

using jquery is the easy way

<div id="result"></div>
<script type="text/javascript>
var x=32;
$('#result').load('echo.php?var='+x);
</script>
share|improve this answer
thanks alot. I used this way. it worked full – زهير طه Jul 15 '12 at 21:16

You can do it by using AJAX to pass the request to the server. You'll need the jQuery get method to do that. Like:

<script>
// You need jQuery for that
$().ready(function() {
  var inputFieldValue = $('input#name').val();
  $.get({
    url: 'index.php'
    data: {var1: "test", var2: inputFieldValue}
  });
});
</script>

And use it in the PHP code as:

<?php 

$var1 = $_GET['var1'];
$var2 = $_GET['var2'];
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.