Converting Javascript variable to a PHP variable

40,395

Solution 1

You don't "convert" it. Send it using a get request or something similar to the php page.

Javascript runs on the client side while php runs on the server side.

There are many different ways you can do this and which one you choose depends on your particular situation. However, I think it's important to check how this all works and for you to make sure you understand the difference between client side and server side.

Check w3c's example. The Javascript part makes a request to the php file when the user chooses a person. The php file then queries the MySQL database and responds to the Javascript file which then in turns presents the result to the user.

The particular code used in this example I would not recommend using in production. The MySQL database information is stored in plain text which anyone could read. I'm using this link purely as a working example of how everything works together.

Solution 2

This will convert js variable to php variable and php variable to js variable

<script>
function jstophp(){


var javavar=document.getElementById("text").value;  

document.getElementById("rslt").innerHTML="<?php 
$phpvar='"+javavar+"'; 
echo $phpvar;?>";
}

function phptojs(){

var javavar2 = "<?php 

$phpvar2="I am php variable value";
echo $phpvar2;

?>";
alert(javavar2);
}

</script> 
<body>
<div id="rslt">
</div>


<input type="text" id="text" />
<button onClick="jstophp()" >Convert js to php</button>
<button onClick="phptojs()">Convert php to js</button>

PHP variable will appear here:
<div id="rslt2">
</div>

</body>

Demo: http://ibence.com/new.php

Solution 3

JavaScript cannot interact with PHP unless it is via an AJAX request. What you would need to do is send it via AJAX to the page, and then use PHP to access the variable.

Share:
40,395
AJ Naidas
Author by

AJ Naidas

Updated on March 16, 2020

Comments

  • AJ Naidas
    AJ Naidas about 4 years

    I would like to use a javascript variable that was returned to me by a videoel.getCurrentTime function and convert it to a php variable for me to able to add it up to my SQL Insert Query like INSERT INTO tblData VALUES ('$phpVarFromJavascript');

  • LoveAndCoding
    LoveAndCoding over 12 years
    Just to clarify, w3schools is not affiliated in any way with the w3c. See w3fools.com for more info.
  • Aidanc
    Aidanc over 12 years
    @Ktash Forgot to add that. I wouldn't recommend w3schools as a great source but it suited the purpose of demonstrating how things work.