Javascript redirect and set cookies

1

I have the following code with Javascript

<script type="text/javascript">
  $(function() {
    $("#loginForm").submit(function(event) {
      $("#success").css("display", "block"), $('#success').html("Autenticando...");
      $('#info').hide();
      $('.form-group').hide();

      var rootUrl = "<?php echo URL_BASE; ?>";

      var username = $("#username").val();
      var password = $("#password").val();

      $.ajax( {
        method: "POST",
        url: "api/login.php",
        dataType: "JSON",
        data: $(this).serialize(),
        success: function(i) {
          if (i["status"] == "success") {
            $("#error").css("display", "none");
            location.href = rootUrl + "/options/?welcome=true";
          } else {
            if (i["status"] == "error") {
              $("#error").css("display", "block"), $("#error").html(i["message"]);
              $("#success").css("display", "none"), $("#success").empty();
              $(".form-group").show();
              $("#info").show();
              return false;
            }
          }
        }, error: function (error) { console.log(error); }
      });
      return false;
    });
  });
</script>

And in my PHP :

if (isset($cookies['auth_token'])) {

  Cookies::set('auth_token', $cookies['auth_token']);
  Cookies::set('user', $ttrUsername);
  Cookies::set('pass', $ttrPassword);

  $_SESSION[SITE_NAME . '_SESSION'] = $ttrUsername;

  echo json_encode(array(
            "status"          => "success",
          "message"     => "Autenticação bem sucedida, estamos te redirecionando.",
        ));

} else {
    echo json_encode(
                array(
                    "status" => "error",
                    'message'=> "Não foi possível autenticar com o Twitter.",
                ));
} 

The problem that Javascript redirects but does not take Cookies together, how to solve this?

EDIT 1

Where

Cookies::set('auth_token', $cookies['auth_token']);

It is equivalent to:

setcookie('auth_token', $cookies['auth_token'], time() + (2 * 3600));
    
asked by anonymous 01.07.2017 / 13:05

1 answer

1

In the PHP manual of setcookie () :

  

Path (path)

     

The path on the server on which the cookie will be available. If   configured to '/', the cookie will be available throughout the domain. If   set to '/ foo /', the cookie will only be available in the directory   / foo / and all subdirectories, such as / foo / bar / domain. O   default value is the current directory in which the cookie is being   configured.

You can do so, like you commented :

setcookie("TestCookie", "Value", time()+3600 , '/' );

Or even if you want available in the main domain and any subdomain, please provide the fifth parameter like this:

setcookie("TestCookie", "Value", time()+3600 , '/', '.example.com' );
    
01.07.2017 / 17:53