3

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?

0

2 Answers 2

3

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>
Sign up to request clarification or add additional context in comments.

2 Comments

No it wont work as I'm echoing the 'a href'. So the quotes are a problem
The answer is echo "<a href='../router/confirmDelete.php?id=$id&username=$userName'><input type='button' class='delete-btn' value='' onclick='return deleteTask()'/></a> <a href='../view/editTask.php?id=$id&username=$userName'><input type='submit' class='edit-btn' value=''/></a>"; and change the script accordingly. <script type="text/javascript"> function deleteTask() { var conBox = confirm("Are you sure?"); if (conBox) { return true; } else { return false; } } </script>
0

Try this

echo "<input type='button' value='Click Here' onclick='deleteTask(id, task, name)' />"

1 Comment

No, this post did not serve my purpose, but rather the first one did. Thanks any how.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.