Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a javascript function in a php web page? [duplicate]

Possible Duplicate:
How to call a JavaScript function from PHP?

I have a php page in which I echo certain things depending on the user privilege (admin or user). I would like to know if I can call a javascript function when a button is clicked.

<?php
if ($_SESSION['access_rights']=='admin') {
     $id = $_GET['id'];
     $userName = $_GET['username'];
     echo "<a href='../view/confirmDelete.php?id=$id&type=task&username=$userName'><input type='button' class='delete-btn' value=''/></a>
           <a href='../view/editTask.php?id=$id&username=$userName'><input type='submit' class='edit-btn' value=''/></a>";
}
?>

The function I would like to call is as follows. This is placed in the head of the page.

<script type="text/javascript">
function deleteTask(id,task,name) {
    var conBox = confirm("Are you sure you wanna delete task assigned to "+ name + " ?");
    if (conBox) {
        location.href="<?=$_SERVER['PHP_SELF'];?>"
    } else {
        return;
    }
}
</script>

I was wondering if the function 'deleteTask()' can be called via a href like

<a href="javascript" deleteTask('<?=id;?>','task','<?=userName?>');">Delete me</a>

else using onclick="deleteTask();

I am required to pass arguments to the function. I am unable to the javascript call in href as it requires quote. Any ideas?

like image 938
Shyam K Avatar asked May 19 '26 05:05

Shyam K


1 Answers

With the quotes directly after javascript you close the href-attribute. Use a : to seperate the keyword javascript and the command:

In PHP (don't forget to escape the quotes):

echo "<a href=\"javascript:deleteTask('$id;','task','$userName');\">Delete me</a>";

or HTML:

<a href="javascript:deleteTask('<?=$id?>','task','<?=$userName?>');">Delete me</a>
like image 180
scessor Avatar answered May 20 '26 17:05

scessor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!