Rana Pratap
Rana Pratap

Reputation: 55

JavaScript not working under php tag

Why is Javascript not working in the following line?

<?php
echo "<a href='admin-advertiser-delete.php?supplier=$row[adv_id]' onclick='if (!confirm('Are you sure?')) return false;'><i class='fa fa-times'></i></a>";
?>

Upvotes: 0

Views: 91

Answers (3)

Takit Isy
Takit Isy

Reputation: 10081

I suggest you to use HEREDOC syntax to get rid ot the problem of escaping quotes:

<?php
echo <<<EOD
<a href='admin-advertiser-delete.php?supplier={$row[adv_id]}' onclick='if (!confirm("Are you sure?")) return false;'><i class='fa fa-times'></i></a>
EOD;
?>

See link for documentation: http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

Note that you won't need to escape quotes but you'll need to use the correct ones: onclick='confirm("Ok?")' is correct, onclick='confirm('Ok?')' isn't.

Hope it helps.

Upvotes: 0

mplungjan
mplungjan

Reputation: 178413

Quotes need to be escaped

  1. onclick=\"if (!confirm('Are you sure?')) return false;\"
  2. better onclick=\"return confirm('Are you sure?')\"
  3. MUCH better: NEVER have a GET link delete things since one visist from google bot will kill your database

echo "<a href='javascriptneeded.html' onclick=\"if (confirm('Are you sure?') location = 'admin-advertiser-delete.php?supplier=$row[adv_id]'; return false;\"><i class='fa fa-times'></i></a>";

  1. BEST:

echo "<a href='javascriptneeded.html' class='deleteAdv' data-id='$row[adv_id]'><i class='fa fa-times'></i></a>";

using

document.querySelectorAll(".deleteAdv").forEach(function(link) {
  link.onclick=function() {
    if (confirm("Are you sure") {
      location = "admin-advertiser-delete.php?supplier="+encodeURIComponent(this.getAttribute("data-id"));
    }
    return false;
  }
});

Upvotes: 3

user3053216
user3053216

Reputation: 809

You are not escaping your quotes. In this part:

onclick='if (!confirm('Are you sure?')) return false;'

The html parser sees the ' before "are you sure" as the ending quote, therefore interpreting it as this:

onclick='if (!confirm('

Therefore you should escape your quotes and it should work:

 onclick='if (!confirm(\'Are you sure?\')) return false;'

Upvotes: 1

Related Questions