Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have declared a javascript variable ,

 var myJavascriptVar = 12345;

And unable to assign that value to php variable;

 $myPhpVar = 'myJavascriptVar'; 

I know Ajax may be the solution of my problem. But i don't know how to use Ajax and solve the problem.

<html>
<body>
<script>
var myJavascriptVar = 12345;
<?php $myPhpVar='myJavascriptVar';?> 
</script>
<?php echo $myPhpVar; ?>
</body>
</html>
share|improve this question
    
You sure you want to give a JS value to PHP? PHP doesn't work on client side. What you are making will give that php the value only for once from your code. It wont give it to php live on client side like that –  Hanky 웃 Panky Feb 7 '14 at 5:42
    
Learn about forms to send data to PHP easily and than learn AJAX for dynamic data exhange. –  Shiva Kumar Avula Feb 7 '14 at 5:43

5 Answers 5

You should see these links:

Assign Javascript value to PHP variable

Passing Javascript vars to PHP

Or you can use AJAX request or POST and GET methods to achieve this.

Snippet below may helpful for you:

<?php 
   if(isset($_POST['isSubmit']))
   {
      // do something here
      echo $_POST["name"];
   }
?> 

<form action="<?php $_SERVER['PHP_SELF'];?>" method="POST"> 
Your name: <input type="text" name="name" /> 
<input type="Submit" value="Submit" name="isSubmit"> 
</form> 
share|improve this answer

Try using ajax with jQuery.post() if you want a more dynamic assignment of variables.

The reason you can't assign a variable directly is because they are processed in different places.

It's like trying to add eggs to an already baked cake, instead you should send the egg to the bakery to get a new cake with the new eggs. That's what jQuery's post is made for.

Alert the results from requesting test.php with an additional payload of data (HTML or XML, depending on what was returned).

$.post( "test.php", { name: "John", time: "2pm" })
  .done(function( data ) {
    alert( "Data Loaded: " + data );
  });
share|improve this answer

Javascript will be interpreted in Client's browser and you can not assign it to PHP variable which is interpreted on SERVER .

Feasible Solution : You can submit the Javascript value via ajax or through form submit.

share|improve this answer

I guess you can use cookies for it.

1) First add a cookie jquery plugin.

2) Then store that window width in a cookie variable.

3) Access your cookie in PHP like $_COOKIE['variable name'].

http://www.w3schools.com/php/php_cookies.asp

share|improve this answer

You can not do this directly for that you should use ajax. For reference you can refer this link

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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