onclick load function in php

I m have 2 my code and one work and when i use code 2 not work.

Javascript is still the same. This is javascript and work

function addto(selid)
{
    var i;
    var item = "";

    for (i = 0; i < 1000; i++) { 
        item = "incart_"+i; 
        if(getCookie(item) == "")
            {  
            setCookie(item,selid,24);  
                break;
            }
    }

}

This code work

    <button onclick='addto("1");' data-toggle="tooltip" title="Add"><i class="fa fa-shopping-cart shop-card-icon"> </i></button >

but when i use php does not respond

// If i use the action in php it goes.

<button  <?php echo "onclick='addto('".$row["id"]. "');'"; ?>  data-toggle="tooltip" title="Add"><i class="fa fa-shopping-cart shop-card-icon"> </i></button>

2 answers

  • answered 2018-10-11 19:05 Jeto

    Use PHP only on the dynamic part:

    <button onclick="addto('<?= $row['id'] ?>')" data-toggle="tooltip" title="Add"><i class="fa fa-shopping-cart shop-card-icon"></i></button>
    

  • answered 2018-10-11 19:12 Salvatore Q Zeroastro

    You have an escaping issue, you can either echo the whole button and use proper escaping on the quotes, or just echo the dynamic part

    Echo just the dynamic part (best option)

    <button  onclick="addto('<?php echo $row["id"]; ?>')" data-toggle="tooltip" title="Add"><i class="fa fa-shopping-cart shop-card-icon"> </i></button>
    

    Echo the whole button

    <?php echo '<button onclick="addto(\''. $row["id"] .'\')" data-toggle="tooltip" title="Add"><i class="fa fa-shopping-cart shop-card-icon"> </i></button>'; ?>