Skip to content Skip to sidebar Skip to footer

How To Store The Value Of A Javascript Variable Into Php Variable?

I need to pass a value from javascript to php. How can i achieve this since one runs on client side and other on server? or any other alternatives for this to happen? I am a newbie

Solution 1:

It is not possible since PHP code (server-side) is run/parsed before javascript code (client side). So what you are doing is not possible although reverse is possible. You can also use:

  • Ajax
  • Hidden form field
  • Query string variable (via url)

To send javascipt variable value to php.

Solution 2:

PHP is server side language, that is used to render output in HTML, so you can assign PHP variable in JavaScript variable not JavaScript to php, you can send JavaScript variable to Server by AJAX

Try this way

<SCRIPTlanguage="JavaScript">var q1=Math.floor(Math.random()*11) 
functionsendAJAX(q1)
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=newXMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=newActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
         alert('posted value' + xmlhttp.responseText);
    }
  }
xmlhttp.open("GET","http://yourdomain.com/?q=" + q1 ,true);
xmlhttp.send();
}
</SCRIPT>

And in PHP code

<?php$ff = $_GET['q'];
echo$ff;
?>

Solution 3:

The HTML file:

<scriptsrc='http://code.jquery.com/jquery-1.10.2.min.js'></script><script>var q1=Math.floor(Math.random()*11);
$(document).ready(function(){
    $.ajax({url:"ajax.php",data: {"q1":q1}}).done(function(data){console.log(data)});
});
</script>

The PHP file: ajax.php

<?php$ff = filter_input(INPUT_GET, 'q1', FILTER_VALIDATE_INT);
echo$ff;
?>

References:

jquery

PHP

Solution 4:

you can use like this.

<html><head><scripttype="text/javascript">var q1="hello"; 

          <?php$ff ="<script>document.write(q1)</script>";             
          ?></script></head><body><?phpecho$ff; ?></body></html>

Solution 5:

you can use like this.

<html><head><scripttype="text/javascript">var q1="hello"; 

          <?php$ff ="<script>document.write(q1)</script>";             
          ?></script></head><body><?phpecho$ff; ?></body></html>

Post a Comment for "How To Store The Value Of A Javascript Variable Into Php Variable?"