-1

I've a script to get a true or false value

var parent = document.getElementById('varför-välja-god-assistans');
var child1 = document.getElementById('cpm-id1');
var child2 = document.getElementById('cpm-id2');
var child3 = document.getElementById('cpm-id3');
if ( parent.contains( child1 ) ) {
var val1 = parent.contains( child1 );
document.cookie = "val1=1";
}
if ( parent.contains( child2 ) ) {
var val2 = parent.contains( child2 );
document.cookie = "val2=2";
}
if ( parent.contains( child3 ) ) {
var val3 = parent.contains( child3 );
document.cookie = "val3=3";
}

From php class, how can I access the value of val1, val2, val3

      $x1 =  $_COOKIE['val1'];
      $x2 =  $_COOKIE['val2'];
      $x3 =  $_COOKIE['val3'];

Simply echoing out above value gives me an error ( Notice: Undefined index: val1 inPopupwidget.php on line 137 )

Any help would be appreciated ( if the above code is incorrect way, please suggest better version )

Thanks !!!

maverick
  • 141
  • 1
  • 13
  • This topic is very similar to [https://stackoverflow.com/questions/5045053/set-cookie-wih-js-read-with-php-problem](https://stackoverflow.com/questions/5045053/set-cookie-wih-js-read-with-php-problem) please refer to it. – Eduardo Palacio Aug 03 '18 at 06:44

2 Answers2

0

Since you have a conditional execution of your code blocks in javascript (if), some or all of you cookies may have not be created. So you should check if they are set before trying to echo them. I would suggest something like that:

if (isset($_COOKIE['val1']) {
    $x1 = $_COOKIE['val1'];
    echo $x1;
}

Or for something less verbose you could use the double ternary operator:

$x1 = $_COOKIE['val1'] ?? null;
iiirxs
  • 4,493
  • 2
  • 20
  • 35
0
<?php
print_r($_COOKIE);

?>
<script type="text/javascript">
//var parent = document.getElementById('varför-välja-god-assistans');
//var child1 = document.getElementById('cpm-id1');
//var child2 = document.getElementById('cpm-id2');
//var child3 = document.getElementById('cpm-id3');
//if ( parent.contains( child1 ) ) {
//var val1 = parent.contains( child1 );
document.cookie = "val1=1";
//}
//if ( parent.contains( child2 ) ) {
//var val2 = parent.contains( child2 );
document.cookie = "val2=2";
//}
//if ( parent.contains( child3 ) ) {
//var val3 = parent.contains( child3 );
document.cookie = "val3=3";
//}
</script>

Result: Array ( [val1] => 1 [val2] => 2 [val3] => 3 )

I think you should check your conditions part.

P.Banerjee
  • 189
  • 2
  • 14