Baron Daniel
Baron Daniel

Reputation: 43

Place a onCLICK inside a PHP echo

I have the following code

<table width="100%" border="1" cellpadding="15" align="center">
<?php
$res = $dbcon->query("SELECT * FROM actor");

while($row=$res->fetch_array())
{
?>
 <tr>
<td><?php echo $row['actor_id']; ?></td>
<td><a href="?del=<?php echo $row['actor_id']; ?>" onclick="return confirm('sure to delete !'); " >delete</a></td>
</tr>
<?php
}
?>

This works fine in every way but the problem is that i cant seem to set the onclick to work onside an echo in this next piece of code. I'm learning mysql/php so i'm experimenting with various codes.

FOR ($j=0 ; $j < $rows; ++$j) {

   $result->data_seek($j);
   $row = $result->fetch_array(MYSQLI_ASSOC);
   echo 'Actor ID: ' . $row['actor_id'] . '<br>';
   echo '<a href="?del='.$row['actor_id'].'">Delete</a>'. '<br><br>';                       
}
$result->close();
$conn->close();
?>

The delete button works i just don't have a warning anymore, i can't figure out how to properly insert onclick="return confirm('sure to delete !')

Upvotes: 1

Views: 16292

Answers (3)

Jsparo30
Jsparo30

Reputation: 405

Yo can make it in another way:

<td><a class="delete" href="?del=<?= $row['actor_id'] ?>" >delete</a></td>

<script>
$(document).ready(function){
$('.delete').click(function(){
var id = $(this).attr('del');
var confirmText = "Are you sure you want to delete this object?";
    if(confirm(confirmText)) {
        $.ajax({
            type:"POST",
            url:url,
            data: 'id=' + id,
            success:function () {
            // Here goes something...
            },
        });
    }
    return false;
});
});
</script>

Upvotes: 0

Robert
Robert

Reputation: 20286

If you use PHP for templates maybe you should consider more template oriented syntax

  <?php while($row=$res->fetch_array()): ?>
  <tr>
      <td><?= $row['actor_id'] ?></td>
      <td><a href="?del=<?= $row['actor_id'] ?>" onclick="return confirm('sure to delete !'); " >delete</a></td>
 </tr>
 <?php endwhile ?>

It will make escaping a lot easier.

Upvotes: 0

Samir Selia
Samir Selia

Reputation: 7065

You will have to escape the quotes. This is what you need

echo '<a href="?del={$row['actor_id']}" onclick="return confirm(\'sure to delete !\');">Delete</a>'. '<br><br>'; 

Upvotes: 7

Related Questions