Samuel Samuel - 6 months ago 16
PHP Question

How to store js variable into php without using $_SESSION["name"] = "<script>document.write(name)</script>";?

I tried using $_SESSION["name"] = "document.write(name)"; and it works if i echo it out. But if i were to show this SESSION variable into a textbox or use it to do SQL, it shows document.write(name). How can i properly store it into a php variable? I've search and many people say you cant convert it. But surely there is someways where i can use the Javascript variable(name) to show it in a textbox or use it in SQL.

javascript code with the variable name.

<script>
var name;
$(document).ready(function()
{
$('#info tr #name').click(function()
{
name = $(this).text();
alert(name);
window.location = 'CV.php';
});
});
</script>


For SQL my code is this,

<?php $_SESSION["name"] = "<script>document.write(name)</script>";
echo $_SESSION["name"];
$connect = mysqli_connect("localhost", "root", "","test1");
$sql = "SELECT Name, Number, Expertise, Status, Remarks FROM particulars WHERE Name ='". $_SESSION["name"]."'";

$result = mysqli_query($connect, $sql);

while($row= mysqli_fetch_array($result))
{
$name = $row['Name'];
$number =$row['Number'];
$Expertise =$row['Expertise'];
$status =$row['Status'];
$remarks =$row['Remarks'];
}
?>


And below is my code to try to show the variable that i have stored in session into textbox.

<input type='text' value='" .htmlspecialchars($_SESSION['name']) . "'/>

Answer
<script>
    var name;
    $(document).ready(function()
    {
    $('#info tr #name').click(function()
    {

        name = $(this).text();
        alert(name);
        window.location = 'CV.php?name=' + name; // send in link

    });
    });
    </script>

Inside CV.PHP

if(isset($_GET['name']))
{
    $name = $_GET['name']; // Get it from URL
    $_SESSION["name"] = $name; 
}
else
{
    $name = $_SESSION['name']; // Get it from session
}
$connect = mysqli_connect("localhost", "root", "","test1");
$sql = "SELECT Name, Number, Expertise, Status, Remarks FROM particulars WHERE Name ='". $_SESSION["name"]."'";

$result = mysqli_query($connect, $sql);

while($row= mysqli_fetch_array($result))
{
   $name = $row['Name'];
   $number =$row['Number'];
   $Expertise =$row['Expertise'];
   $status =$row['Status'];
   $remarks =$row['Remarks'];
} ?>

To show it in input box:

    <input type='text' value='" .$name . "'/> // echo value as string
    <input type='text' value='" .$_SESSION['name']. "'/> // if it's a page that is not CV.php