简体   繁体   中英

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.

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>

你可以试试这个

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM