how to get javascript variable value in php in same page?

Today, We want to share with you how to get javascript variable value in php in same page.In this post we will show you pass javascript variable to php same page ajax, hear for passing javascript variable to php in the same page we will give you demo and example for implement.In this post, we will learn about how to pass value from one page to another in php with an example.

how to store javascript value in php variable?

You can’t get a js variable directly in PHP server code, you have create a PHP HTTP request with data (Like as a as your $.ajax() request above) after that use $_POST or $_GET in PHP to fetch the value.

first of all include jquery library file in HTML Code.

Read Also:  How to get CSS class Name Property using Jquery

HTML Code

<div id="results-display"></div> 

Javascript

$(document).ready(function(){ 
var url = window.location.href; 
var all_datas = url.split('?ID='); 
var id = (all_datas[1]); 
        $.ajax({ 
        type:"POST", 
        url:"page.php", 
        data:{id:id}, 
        success:function(outputs){ 
        $("#results-display").html(outputs); 
        } 
        }); 
   }); 

PHP : domain-name.php

<?php 
$random = $_POST["id"]; 
echo $random; 
?> 

Complete One page code:

domain-name.php

ipt> 
$(document).ready(function(){ 
var url = window.location.href; 
var all_datas = url.split('?ID='); 
var id = (all_datas[1]); 
     $("#productsave").click(function(){ $.ajax({ 
        type:"POST", 
        url:"demo.php", 
        data:{id:id}, 
        success:function(outputs){ 
        $("#results-display").html(outputs); 
        $("#productsave").hide(); 
        } 
        }); 
        }); 
   }); 
   </script> 
</head> 
<body> 
<button id="productsave">Click Me</button> 
<div id="results-display"></div> 
 
</body> 
</html> 
<?php 
$genrated_product_GGID = $_POST["id"]; 
echo $genrated_product_GGID; 
?> 

Note: URL for this page must be domain-name.php?Id=someValue

Read Also:  JavaScript Client side Password hashing and encryption

How to pass JavaScript variables to PHP?

simply get the JavaScript variable value on the same page in PHP

<script>
   var res = "Good Luck!!!!";
</script>
<?php
   echo "<script>document.writeln(res);</script>";
?>

I hope you get an idea about how to assign jquery variable value to php variable in same page?.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.