Skip to content
Advertisement

Can’t set cookie on different domain

This URL has the code below: https://trywifibooster.com/test/setCookiesFromAnotherDomain.html?param=SHOULD-SET-TO-THIS

var params = new window.URLSearchParams(window.location.search).get('param');

$.ajax({

  type: 'GET',
  crossDomain: true,
  url: 'https://go.allthatstrendy.com/intercart/cookies/Test/saveCookies2.php',
  data: 
  "UTMParamsString=" + params,

  //success
  success:function(data) {

    console.log(data);

  },
  //error
  error:function(xhr, options, error) {
     console.log("Cookies not successfully saved" + error);
  }
});

alert("Sent: " + params);

Which should take in the variables passed in the URL. Then save it to this domain as a cookie go.allthatstrendy.com. It’s done through a PHP script executed by AJAX.

The PHP script:

<?php

    // Headers
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Credentials: true");
    header("Access-Control-Allow-Methods: GET, POST");
    header("Access-Control-Allow-Headers: Content-Type, *");

    if(isset($_GET['UTMParamsString'])) {

        $UTMParamsString = $_GET['UTMParamsString'];

        setcookie("UTMParamsString", $UTMParamsString, time()+3600, "/", "allthatstrendy.com", 1);

    }

    echo "GET VARIABLE: " . $UTMParamsString;

    echo "<br/>";

    echo "CHECK COOKIE WAS SET: " . $_COOKIE['UTMParamsString'];

?>

However, when the Ajax on trywifibooster.com is executed, leading to go.allthatstrendy.com, no cookies are set.

After running the URL above. Go to https://go.allthatstrendy.com/intercart/ and check the cookies. It’s not set!

I’ve even set it up so you can execute a script directly on go.allthatstrendy.com and set the cookie directly there. It works like that.

See: https://go.allthatstrendy.com/intercart/cookies/Test/saveCookies2.php?UTMParamsString=TESTjhghgjghj

However, when I try and set the cookie here https://trywifibooster.com/test/setCookiesFromAnotherDomain.html?param=SHOULD-SET-TO-THIS

It doesn’t set it. There is no cross-origin error or anything. I’ve gone back and forth for over 3 hours and I’m honestly about to scream. It makes no sense. I am an experienced developer. So it makes it even more frustrating!

Advertisement

Answer

XHR doesn’t send or accept cookies unless you explicitly enable credential support:

$.ajax({
  type: 'GET',
  xhrFields: {
    withCredentials: true
  }

Note that this will make your request preflighted.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement