user2139846
user2139846

Reputation: 21

Storing User Preferences in Cookie

I'm creating a website in php using which allows users to filter the content displayed through checkboxes. I want to save their preferences. I'm using jquery.mmenu and generating the checkboxes as follows

<form id="menu-right method="post" action="">
<li>
<a href="">'. $sportArray[$ids]["Event"] . '</a>
<input type="checkbox" class="Toggle" name="sportList[]" value="'.$sportArray[$ids]["Event"].'" />
</li>'
</form>

I'm able to collect an array and print the values of the array through the below code, but I'm unable to set cookies, retrieve cookies, and haven't even started adding a check in the checkbox to restore the 'checked' values when loaded the checkboxes. I've tried a number of methods through javascript and php with no luck. There are pseudo elements in the CSS which I understand broke a couple of options for javascript

<?
if(isset($_POST['sportList'])) { 
for ($i=0; $i<=count($_POST['sportList']); $i++){
    echo $_POST['sportList'][$i];
    setcookie('userSportList[$i]', $_POST['sportList'][$i], time()+60*60*24*365, '/');
} 
}
?>

Any solution welcome.. it's probably something stupid at this stage as I'm tried so many options now. Alternatives such as localstorage or something also welcome, what ever is the best solution

<?php
            if(isset($_POST['sportList'])) { 
                session_start();
                $_SESSION['sesUserPrefs'] = $_POST['sportList'];

                $serUserPrefs = serialize($_SESSION['sesUserPrefs']);
                $bcSerUserPrefs = base64_encode($serUserPrefs);

                $expire = 2000000000;
                setcookie("cUserPrefs", $bcSerUserPrefs, time()+$expire);

            }
?>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html;charset=iso-8859-1" />

        <title>test
        </title>

        <link type="text/css" rel="stylesheet" href="css/main.css" />
        <link type="text/css" rel="stylesheet" href="css/mmenu.5.3.css" />


        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/hammer.js/1.0.5/jquery.hammer.min.js"></script>
        <script type="text/javascript" src="js/umd.all.js"></script>
        <script src="http://cdn.jsdelivr.net/jquery.cookie/1.4.0/jquery.cookie.min.js"></script>

        <script type="text/javascript">

            //  The menu on the left
            $(function() {
                $('nav#menu-left').mmenu();
            });


            //  The menu on the right
            $(function() {

                var $menu = $('form#menu-right');

                $menu.mmenu({
                    offCanvas: {
                       position : "right"
                    },
                    classes     : 'mm-light',
                    dragOpen    : true,
                    counters    : true,    
                     searchfield: {
                        add: true,
                        search: false
                    },
                    labels      : {
                        fixed       : !$.mmenu.support.touch
                    },
                    navbars: {
                        position:   "top",
                         content: [
                                    '<a href="javascript:document.getElementById(\'menu-right\').submit();">Save</a>'
                            ]
                         }

                });

            });
        </script>
    </head>
    <body>
    <?php
    // DB Configuration
$config = parse_ini_file('config/config.ini'); 


    //Timezone dropdown
function timezone() {    
    $list = DateTimeZone::listAbbreviations();
    $idents = DateTimeZone::listIdentifiers();

    $data = $offset = $added = array();
    foreach ($list as $abbr => $info) {
        foreach ($info as $zone) {
            if ( ! empty($zone['timezone_id'])
                AND
                ! in_array($zone['timezone_id'], $added)
                AND
                  in_array($zone['timezone_id'], $idents)) {
                $z = new DateTimeZone($zone['timezone_id']);
                $c = new DateTime(null, $z);
                $zone['time'] = $c->format('h:i a');
                $data[] = $zone;
                $offset[] = $z->getOffset($c);
                $added[] = $zone['timezone_id'];
            }
        }
    }

    array_multisort($offset, SORT_ASC, $data);
    $options = array();
    foreach ($data as $key => $row) {
        $options[$row['timezone_id']] = $row['time'] . ' - '
                                        . formatOffset($row['offset'])
                                        . ' ' . $row['timezone_id'];
    }

    return $options;
}
function formatOffset($offset) {
        $hours = $offset / 3600;
        $remainder = $offset % 3600;
        $sign = $hours > 0 ? '+' : '-';
        $hour = (int) abs($hours);
        $minutes = (int) abs($remainder / 60);

        if ($hour == 0 AND $minutes == 0) {
            $sign = ' ';
        }
        return 'GMT' . $sign . str_pad($hour, 2, '0', STR_PAD_LEFT)
                .':'. str_pad($minutes,2, '0');

}
?>
        <div id="page">
            <div id="header">
                <a href="#menu-left"></a>
                        <!-- Sub Header -->
                    <form id="tzForm" method="POST" action="">
                    <select name="userTZ" >
                    <?php foreach(timezone() as $key => $tz) { ?>
                    <option value="<?php echo $key; ?>"<?php if ($_POST['userTZ'] == $key) { echo ' selected>';} else { echo '>';} //keep tz as last selected 
                     echo $tz; ?></option>
                    <?php } ?>
                    </select> <input type="submit" value="Set">

                    </form>
                <a href="#menu-right" class="friends right"></a>
            </div> <!-- Close Header -->
            <div id="content">


                <?php


                                //Collect Selected Sport/Category/Event values from right menu

                    if (isset($_COOKIE["cUserPrefs"])) {
                    echo "<script type='text/javascript'>alert('ding ding ding');</script>";
                    } elseif (isset($_SESSION['sesUserPrefs'])) {

                            $sportListItem = $_SESSION['sesUserPrefs'];

                        //update array with selected toggles
                while ($row = $result->fetch_array()) {
                    if ($row['SportCategory'] == $sportListItem OR $row['Sport'] == $sportListItem OR $row['Event'] == $sportListItem)  {
                    $gameArray[ $row['PK_ID'] ] = array(
                                'GameDate' => $row['GameDate'],
                                'Timezone' => $row['Timezone'],
                                'TeamOne' => $row['TeamOne'],
                                'TeamTwo' => $row['TeamTwo'],
                                'urlTeamOne' => $row['urlTeamOne'],
                                'urlTeamTwo' => $row['urlTeamTwo'],
                                'FK_SportData' => $row['FK_SportData']
                                );
                                } //end inside if

                                }; 

                } 


                ?>

            </div>

        <div id="page">

            <div id="content">
                <p id="confirmation"></p>
            </div>
            <nav id="menu-left">
                <?php
                foreach ($sportArray as $ids=>$vals) {

                    //First List Item
                if ($ids == 1) {
                    echo '<ul><li>
                            <a href="?SportID='.$sportArray[$ids]["SportCategory"].'">'. $sportArray[$ids]["SportCategory"]. '</a>
                            <ul class="Vertical">'; 
                         }  
                            //All others check if different to one before
                         elseif ($sportArray[$ids]["SportCategory"] != $sportArray[($ids - 1)]["SportCategory"]) {
                                echo '</ul></li></ul></li><li>
                                        <a href="?SportID='.$sportArray[$ids]["SportCategory"].'">'. $sportArray[$ids]["SportCategory"] . '</a>
                                        <ul class="Vertical">';  //opening thse UL without an event could cause issues
                            }

                    //Check the previous sport is not the same
                if  ($sportArray[$ids]["Sport"] != $sportArray[($ids - 1)]["Sport"]) {
                    echo '<li>
                            <a href="?SportID='.$sportArray[$ids]["Sport"].'">'. $sportArray[$ids]["Sport"] . '</a>
                            <ul class="Vertical">'; 
                        }
                        //Print Event
                    echo '<li>
                            <a href="?SportID='.$sportArray[$ids]["Event"].'">'. $sportArray[$ids]["Event"] . '</a>
                            </li>';


                }

                ?>
                </ul></li></ul></li></ul>   
            </nav>
            <form id="menu-right" method="post" action="">
            <?php
                foreach ($sportArray as $ids=>$vals) {
                    //First List item
                if ($ids == 1) {
                    echo '<ul class="Vertical"><li>
                            <a href="">'. $sportArray[$ids]["SportCategory"]. '</a>
                            <input type="checkbox" class="Toggle" name="sportList[]" value="'.$sportArray[$ids]["SportCategory"].'" />
                            <ul class="Vertical">';
                         }  
                            //All others check if different to one before
                         elseif ($sportArray[$ids]["SportCategory"] != $sportArray[($ids - 1)]["SportCategory"]) {
                                echo '</ul></li></ul></li><li>
                                        <a href="">'. $sportArray[$ids]["SportCategory"] . '</a>
                                        <input type="checkbox" class="Toggle"  name="sportList[]" value="'.$sportArray[$ids]["SportCategory"].'" />
                                        <ul class="Vertical">'; //opening thse UL without an event could cause issues
                            }

                    //Check the previous sport is not the same
                if  ($sportArray[$ids]["Sport"] != $sportArray[($ids - 1)]["Sport"]) {
                    echo '<li>
                            <a href="">'. $sportArray[$ids]["Sport"] . '</a>
                            <input type="checkbox" class="Toggle" name="sportList[]" value="'.$sportArray[$ids]["Sport"].'" />
                            <ul class="Vertical">';
                        }
                        //Print Event
                    echo '<li>
                            <a href="">'. $sportArray[$ids]["Event"] . '</a>
                            <input type="checkbox" class="Toggle" name="sportList[]" value="'.$sportArray[$ids]["Event"].'" />
                        </li>';


                }

                ?>
                </ul></li></ul></li></ul>   
            </form>
        </div>
    </body>
</html>

Upvotes: 2

Views: 3307

Answers (1)

Zartash Zulfiqar
Zartash Zulfiqar

Reputation: 103

You should use session array for this. First store values into a session. Then you need to :

Serialize your session array and apply base64_encode. Put this value into cookie.

At the start check if cookie exist then apply base64_decode and unserialize that data and push into session array.

If you know about serialize, unserialize, base64_encode and base64_decode then you can easily do this task.

Hopefully you will done this easily.

Upvotes: 1

Related Questions