Elshan
Elshan

Reputation: 7693

Correct way to set cookie from jQuery and read from php

I've tried to read the cookie values in PHP that are set via jQuery. But it's not read in first time page load. But I saw it's already set by the jQuery and can read the same value from the jquery.

When trying to read that cookie value from PHP it's not display the value when page rendered first time. But again refresh the page it's give the value from php.(I need to refresh page 2 time to get the correct value)

I used both head tag and onload method to place the setCookie() function. But result was same.

I used this jQuery library to write cookie.

Here's code I used to read and write the cookie.

<?php
    if (!isset($_SESSION)) {
        session_start();
    }
    ?>
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title></title>
            <style>
                body{
                    background: #666666;
                }
            </style>
            <script src="js/jquery.min.js" type="text/javascript"></script>
            <script src="js/jquery.cookie.js" type="text/javascript">/script>
            <script>
                setCookie();
                function setCookie() {
                    console.log('on Load');
                    var data_spl = $(location).attr('href').split('#?camlist=')[1];
                    if (data_spl != undefined) {
                        var len = data_spl.split(',').length;
                        $.cookie("len", len);
                        console.log($.cookie("len"));
                    } else {
                        console.log('undefined');
                    }
                }
            </script>
        </head>
        <body>           
            <?php
            for ($i = 0; $i < 100; $i++) {
                echo "<script>console.log('START');</script>";
                echo "<script>console.log('" . $_COOKIE['len'] . "');</script>";
                echo $_COOKIE['len'];
                echo "<script>console.log('END');</script>";
            }
    
            echo "WIDTH & HEIGHT :" . $_SESSION['width_x'] . "-" . $_SESSION['height_y'];
            ?>        
        </body>
    </html>

EDITED:

I used another php page to set session value that are came from java script and call that page via jQuery like shown in bellow.

var len = $(location).attr('href').split('#?data=')[1].split(',').length;
$.post('set_session.php', {params: len}, function (retparams) {
      if (retparams.has) {
         console.log('sucessfuly sent the paramlen!');             
      } else {
         alert("can't read camarauids for grid making");
      }
}, 'retparams');

set_session.php

<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
    $_SESSION['urllen'] = 0;
}
if (isset($_POST['params'])) {
    $_SESSION['urllen'] = $_POST['params'];
    echo json_encode(array('retparams' => 'has'));
    echo json_encode(array('datalen' => $_SESSION['urllen']));
} else {
    echo json_encode(array('retparams' => 'error'));
}
?>

Then I try to read the session value ($_SESSION['urllen']) from index.php page. But it's also same as the above.(I need to refresh page one more time to get the correct value that are set from the jQuery post function.)

Upvotes: 0

Views: 2605

Answers (2)

Chris Nissen
Chris Nissen

Reputation: 43

As already mentioned in the comment section your Cookie isn't present on first page Load because it isn't set yet. (If you set the Cookie directly in JS or via AJAX is essentially the same)

The only way to effectively get the Information is ether with a page reload or a redirect or via AJAX request (depends on what fits your needs). For Example you could redirect in JS after the Cookie got set with:

//set your cookie in JS
window.location = location.host; 

more Information about JS redirects can be found here or you search your way thru Google.

You can also set your Cookie in PHP and redirect with the header() function:

header('Location: http://www.example.com/');

More Information for PHP redirects can be found here or on Google ;)

Upvotes: 1

cili
cili

Reputation: 317

You could check this with ajax. Here is a simple example:

<?php
  if(isset($_GET["checkIfLoggedIn"]) && boolval($_GET["checkIfLoggedIn"]) === true) {
    header("Content-Type: text/json");
    die(json_encode(array("isLoggedIn" => $_COOKIE["isLoggedIn"])));
    exit();
  } else {
    var_dump($_COOKIE);
  }
?>

<html>

  <head>
    <script type="text/javascript" src="jquery-3.1.1.min.js"></script>
    <script type="text/javascript" src="js.cookie.js"></script>
  </head>

  <body>
    <script type="text/javascript">
      function checkIfLoggedIn() {
        console.log("checking...");

        jQuery.post("?checkIfLoggedIn=1", function(data) {
          if(data.isLoggedIn == true) {
            alert("Logged im.");
          } else {
            alert("NOT logged in!");
          }
        });
      }
    </script>

    <a href="#" onclick="Cookies.set('isLoggedIn', 'true'); checkIfLoggedIn(); return false;">Set logged in to true</a><br/>
    <a href="#" onclick="Cookies.set('isLoggedIn', 'false'); checkIfLoggedIn(); return false;">Set logged in to false</a>

  </body>

</html>

Upvotes: 0

Related Questions