Search code examples
phpsessionhttp-redirectsession-variables

change php session value by click


i want to give a value to a session by clicking on

i tried to do this , but its not working:

<?php session_start(); 
$_SESSION['role']="";?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
   <head>
<title></title>
<link href="auth-buttons.css" rel="stylesheet" />
<link href="StyleSheet.css" rel="stylesheet" />
   </head>
<body>

<div id="wrap">
<div id="wrapHome">
<p><a class="btn-auth btn-facebook large" href="redirect.php" onclick="<?php $_SESSION['role']="facebook" ?>" > Sign in with <b>Facebook</b> </a></p>

<p><a class="btn-auth btn-twitter large" href="redirect.php" onclick="<?php $_SESSION['role']="twitter" ?>" > Sign in with <b>Twitter</b> </a></p>

<p><a class="btn-auth btn-google large" href="redirect.php" onclick="<?php $_SESSION['role']="google" ?>" > Sign in with <b>Google</b> </a></p>
</div>
</div>
</body>
</html>

Solution

  • 'onclick' will not fire php code. It will trigger javascript though. You can use javascript to make AJAX calls to a php page that'd in turn be able to set your session values (and ajax would help you do so without a page refresh on the button click.

    #('.btn-auth btn-facebook large').click(function(){
    // fire off the request to /redirect.php
    request = $.ajax({
        url: "/redirect.php",
        type: "post",
        data: 'facebook'
    });
    
    // callback handler that will be called on success
    request.done(function (response, textStatus, jqXHR){
        // log a message to the console
        console.log("Hooray, it worked!");
    });
    
    // callback handler that will be called on failure
    request.fail(function (jqXHR, textStatus, errorThrown){
        // log the error to the console
        console.error(
            "The following error occured: "+
            textStatus, errorThrown
        );
        });
    });
    

    In your redirect.php

    <?php
    
    $_SESSION['role'] = $_POST['data'];
    
    ?>