简体   繁体   中英

Pass PHP Variable to Javascript function from Button

Here's what I got.

<script type="text/javascript">
function show_confirm(id)
{
var r=confirm("Are you sure you want to duplicate this record?");
if (r==true)
  {
  window.open ("http://domain.com/process.php?duplicate=id","mywindow");
  }
else
  {
  alert("Record Not Duplicated.");
  }
}
</script>

then below that:

$query = "SELECT * FROM contacts";
        $result = mysql_query($query);      

        while($row = mysql_fetch_row($result)){

                $id = $row[0];
                $company = $row[3];
                $firstName = $row[4];
                $protection = $row[20];

            echo '<tr>';
            echo '<td width="120" align="middle"><font color="black"><b>' . $company . '</b></font></td>';
            echo '<td width="120" align="middle"><font color="black"><b>' . $firstName . '</b></font></td>';

            echo "<td width='120' align='middle'><a style='text-decoration: none;' href='http://domain.com/index.php?id=14&edit=" . $id . "'><span style='font-family:Helvetica; color:black;'>Edit</span></a>";
            echo "<td width='120' align='middle'><input type='button' onclick='show_confirm($id)' value='Duplicate' />";

            echo "</td>";               
            echo '</tr>';


        }
        ?>

The problem is this:

echo "<td width='120' align='middle'><input type='button' onclick='show_confirm($id)' value='Duplicate' />";

This is supposed to be a button where when the user clicks it, it says "are you sure you want to duplicate?" then if the use clicks yes, it to http://domain.com/process.php?duplicate=(whatever the ID is)

The problem is my variable (in php) $id , isn't getting passed to the javascript window.open . I need the $id from the row to be passed along in the javascript. I tried writing it, but it didn't work. Doesn't even see the variable. I've tried manually entering in <?php echo $id; ?> <?php echo $id; ?> and that didn't work as well.

Thank you

window.open ("http://domain.com/process.php?duplicate=id","mywindow");

The URL is the string "http://domain.com/process.php?duplicate=id" . You need to concat the variable to the string. LIke this:

"http://domain.com/process.php?duplicate="+id

It should look like this:

window.open ("http://domain.com/process.php?duplicate="+id,"mywindow");

In order to pass the id, you must use the variable:

window.open ("http://domain.com/process.php?duplicate=" + id,"mywindow");

(you put it in the string)

您必须通过使用JavaScript中的字符串连接运算符(即+)来进行正确的串联操作。正如您所看到的,您要做的就是将id变量附加到URL字符串。

window.open ("http://domain.com/process.php?duplicate="+ id ,"mywindow");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM