0

I have a list of users with a checkbox. Everytime a checkbox is checked, a function is called. The function gets the userid from the checkbox and this userid should be added into a php array and then into a cookie. If the cookie does not exist yet, it should be created. The value of the cookie should be the JavaScript parameter which is passed to this function (id).

My problem is that I don't know how to make this dynamically. E.g. when there is no userid yet in a cookie, it should be added to variable[0]. Furthermore, how can I pass the JavaScript id variable to PHP to set it as cookie value?

This is what I have tried so far:

function loadUserCalendar(id) {
    console.log('user selected: ' + id);

    // check if user is checked or not
    if($('input[value="' + id+ '"]').is(':checked')) {
        console.log('user ' + id + ' is checked now');

        // add user to cookie
        <?php
              $calendar_users = $_COOKIE['calendar_users'];

              if(empty($calendar_users)) {
                  session_start();
                  setcookie("calendar_users[" + $calendar_users.length + 1 + "]", "id", time()+3600*24*30*12);
                  session_commit();
        ?>
                  console.log('added user to cookie');
        <?php

              } else {
        ?>
                  console.log('going to add user to existing cookie');
        <?php
              }
        ?>

    } else {
        console.log('user ' + id + ' is UN-checked now');
        // remove user from cookie
    }
}

Any help is appreciated! Thank you.

nimrod
  • 5,595
  • 29
  • 85
  • 149
  • Are you aware that: 1) JavaScript and PHP don't run simultaneously? 2) Cookies are cookies: there's no thing as "PHP cookie" and JavaScript is perfectly capable of setting cookies itself. – Álvaro González Jul 04 '13 at 09:00
  • No I am not, that's why I am asking. If there is a way to do it without PHP, even better! – nimrod Jul 04 '13 at 09:01

1 Answers1

0

If you want to pass a variable from javascript to php you need to use AJAX, and you need to save it for example in a session or database.

Remember that php is a server side language, connection to the server closes after you receive a response. To send data to the server you either have to refresh the whole page, or use AJAX.

Also, there is no distinction between javascript cookies an php cookies - they are the same.

Check out this website how to set cookies in js http://www.w3schools.com/js/js_cookies.asp

Also, if you're using jquery it's much easier:

$.cookie('somecookie', 1);

How do I set/unset cookie with jQuery?

But you need to use a plugin for that https://github.com/carhartl/jquery-cookie

Community
  • 1
  • 1
Ziarno
  • 7,366
  • 5
  • 34
  • 40