-1

I am trying to set cookies using javascript. but PHP is not working in javascript code. I can alert first value compprd but evrything else is just not working.

<th><input type="button" onClick="setting_my_first_cookie(<?php echo $compprd; ?>)" value="compare">

On click I run this Javascript function:

<script type="text/javascript"> 

function setting_my_first_cookie(compprd) {
alert("welcome"+compprd);
<?php 
    $compcount = 5;

    if (!isset($_COOKIE['compareid_1'])){$comparid = 'compareid_1'; $compcount = 1;}
    elseif (!isset($_COOKIE['compareid_2'])){$comparid = 'compareid_2';$compcount = 2;  }
    elseif (!isset($_COOKIE['compareid_3'])){$comparid = 'compareid_3';$compcount = 3;  }
    elseif(!isset($_COOKIE['compareid_4'])){$comparid = 'compareid_4'; $compcount = 4;  }

    if($compcount <= 4){
    ?>
var compid = <?php echo $comparid;?>
    //alert("create cookie"+compid);
var d = new Date();
    d.setTime(d.getTime() + (30*24*60*60*1000));
    var expires = "expires="+d.toUTCString();   
        document.cookie = compid + "=" + compprd + "; " + "expires; path=/; domain=.domain.com";
    <?php } ?>
}
</script>

Whats the problem here? How to use PHP in javascript?

UPDATE:

here is the code right now I am seeing using View Source:

<script type="text/javascript"> 
function setting_my_first_cookie(compprd) {
alert("welcome"+compprd);
var compid = compareid_1;
    alert("create cookie"+compid);
var d = new Date();
    d.setTime(d.getTime() + (30*24*60*60*1000));
    var expires = "expires="+d.toUTCString();   
        document.cookie = compid + "=" + compprd + "; " + "expires; path=/; domain=.mywebsite.com";
    }
</script>
Rocky Sena
  • 481
  • 1
  • 5
  • 15

2 Answers2

1

Take a look at this line:

 var compid = <?php echo $comparid;?>

It will render as this:

 var compid = compareid_1

But you need to render this:

 var compid = "compareid_1";

So you need to change the line to this:

 var compid = "<?php echo $comparid;?>";

Note the ; and the quotes "

Marcos Pérez Gude
  • 21,869
  • 4
  • 38
  • 69
0

You've missed the (;) in var compid = <?php echo $comparid;?> it should var compid = <?php echo $comparid;?>;

Edit:

You need to change var compid = compareid_1; to var compid = 'compareid_1'; in php it will be var compid = '<?php echo $comparid;?>';

FrozenFire
  • 671
  • 14
  • 28
  • I am getting this error in console: `Uncaught ReferenceError: compareid_1 is not definedsetting_my_first_cookie @ (index):665onclick @ (index):802 Navigated to http://mywebsite.com/websiteurl/` – Rocky Sena Jan 18 '16 at 09:00
  • Can you show your js code using view page source? Since php will modify it when retrieved on browser. – FrozenFire Jan 18 '16 at 09:07
  • I update the code. Please check it – Rocky Sena Jan 18 '16 at 09:12