user13286
user13286

Reputation: 3075

Echoing Javascript within PHP?

I am trying to generate a delete button in my PHP which will delete a row from the database on click. I would also like to throw a confirmation message via Javascript within this link but can't seem to figure out how to structure the code.

Here is what I have so far:

echo "<td class='delete'><a href='?page=db&amp;delete=".$row->id."' onclick='return confirm('are you sure?')'>Delete</a></td>";

I am guessing the reason this isn't working is due to the double/single quotes. Can anyone tell me how I would format this properly? Thank you.

Upvotes: 0

Views: 67

Answers (2)

Quentin
Quentin

Reputation: 943563

You can either use:

  • Double quotes (which would have to be escaped for PHP)
  • Character references for single quotes
  • Character references for double quotes

Such

onclick='return confirm(\"are you sure?\")'>

That said, I'd rewrite this to not have JavaScript nested inside HTML inside PHP inside HTML since that just becomes horrible to try to track.

<td class='delete'>
   <a href="?page=db&amp;delete=<?php echo $row->id; ?>" 
      class="delete">Delete</a>
</td>

and then, using jQuery because it is convenient for this kind of event binding:

<script>
    jQuery("a.delete").on('click', function (evt) {
        if (! confirm('are you sure?')) {
            evt.preventDefault();
        }
    });
</script>

Since you shouldn't do unsafe operations using a GET request, I'd even go a step further and use a form.

<td class='delete'>
   <form method="post">
       <input type="hidden" name="page" value="db">
       <button name="delete" value="<?php echo $row->id; ?>">
           Delete
       </button>
   </form>
</td>

<script>
    jQuery("td.delete > form").on('submit', function (evt) {
        if (! confirm('are you sure?')) {
            evt.preventDefault();
        }
    });
</script>

Upvotes: 5

MH2K9
MH2K9

Reputation: 12039

You can try this

echo '<td class="delete"><a href="?page=db&amp;delete='.$row->id.'" onclick="return confirm(\'are you sure?\')">Delete</a> </td>';

Upvotes: 1

Related Questions