0

I'm just starting with php and I want to save the value of an HTML input to the php session. i have tried achieving this using

<html lang="en">
<head>
    <title>Log In</title>
</head>
<body>
    <?php
    session_start();
    ?>
    <input id='email' type='text' placeholder='Email'>
    <input type='submit' onclick='logIn()' value='Log In'>
</body>
<script>
    function logIn() {
        var email = document.getElementById('email')
        <?php
        $_SESSION['email'] = email;
        ?>
    }
</script>
</html>

but php does not have access to the email variable i created in JavaScript.

I just want to save to the PHP session, data that was entered into an input field of a html site

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
heyt0pe
  • 530
  • 7
  • 18
  • For one, you're probably outputting before header, most likely. Enable error reporting. – Funk Forty Niner Mar 02 '20 at 15:39
  • `$_SESSION['email'] = email;` < that too will trigger an error, being an undefined constant. – Funk Forty Niner Mar 02 '20 at 15:40
  • 4
    This is a prime candidate for AJAX. – Jeremy Harris Mar 02 '20 at 15:41
  • 2
    _“but php does not have access to the email variable i created in JavaScript”_ - if that came as a surprise to you, then you should perhaps have a good, thorough read of [What is the difference between client-side and server-side programming?](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) first of all. – CBroe Mar 02 '20 at 15:43

1 Answers1

0

Use Ajax how suggest from @Jeremy Harris

Script:

function logIn() {
    var email = document.getElementById('email');
    $.ajax({
                url: "session.php",
                type: "POST",
                 data: {
            email:email
        },

                success: function(data){
                         window.location.href = WHERE YOU WANT;
                }        
           }); }

PHP (session.php):

$email=$_POST['email'];
$_SESSION['email'] = $email;
Simone Rossaini
  • 8,115
  • 1
  • 13
  • 34