onclick function in php variable

时间:2015-10-06 08:19:19

标签: javascript php html

How to add onClick event on <a> tag which contains php variables

$delete = "<a onclick='return confirmDelete('deleterecord.php?chkid=$sl&table=$getid&path=$validURL');'><img src='images/dustbin.png' width='43px' height='30px'></a>";  // link not pass

//script

<script>
    function confirmDelete(delUrl) {
        if (confirm("Are you sure you want to delete")) {
            window.location = delUrl;
        }
    }
</script>

2 个答案:

答案 0 :(得分:0)

Use php's echo to return html/css/js stuff: http://php.net/manual/de/function.echo.php

<?php
$delete = "
    <a onclick='confirm_(\"deleterecord.php?chkid=$sl&table=$getid&path=$validURL'\")'; class='link'>
        <img src='images/dustbin.png' width='43px' height='30px'>
    </a>";
echo($delete);
?>
<script>
function confirm_(url){
        console.log(url);
        if (confirm("Are you sure you want to delete")){
            window.location = url;
        }
}
</script>

Like Rayon Dabre sayed, you have to escape string.


Maurize's casual/smart/lazy solution:

You should echo a link with a path like delete.php?action=delete&id=2

and on php side

if (isset($_GET["action"]) && $_GET["action"] == "delete"){ echo $_GET["id"]; }

Will looks like:

<?php
if (isset($_GET["action"]) && $_GET["action"] == "delete"){
    echo $_GET["id"];
}
?>
<a href="index.php?action=delete&id=1">Lazy Casual?</a>

or

<?php
echo("
<a href='deleterecord.php?chkid=$sl&table=$getid&path=$validURL'>
    <img src='images/dustbin.png' width='43px' height='30px'>
</a>
");
?>

Tested and works like mexican.

  • The masterpiece of deletion would be using AJAX + JS - Maurize

答案 1 :(得分:0)

1. $link = "deleterecord.php?chkid=$sl&table=$getid&path=$validURL";

and use

return confirmDelete(\"<?=$link?>\")

2. Escape single quotes by using black slash before single quote:

  <img src=\'images/dustbin.png\' width=\'43px\' height=\'30px\'>