1

echo "<tr onclick='window.location=("www.google.com")'>
      <td>something</td>
      <td>something</td>
    </tr>"

i have written code like this but it is not working.i dont know where to put single quotes and double qoutes. I dont know how to write onclick for in php please suggest me

Ashok Khot
  • 461
  • 4
  • 16

1 Answers1

4

Avoid using echo for HTML. Leave PHP mode and go into output mode.

Avoid using nested literal values. Write each language as a separate variable, use suitable escaping functions to add whatever quotes you need and then put them together.

By keeping everything as separate layers and dealing with them one at a time, and by using functions instead of trying to write your escapes manually, you make things much easier to maintain.

$url = "http://www.google.com";
$js_string_literal_url = json_encode($url);
$js = "window.location = $js_string_literal_url";
$html_safe_js = htmlspecialchars($js);

?>
<tr onclick="<?php echo $html_safe_js; ?>">
  <td>something</td>
  <td>something</td>
</tr>

That said, you should also avoid:

  • Features which depend entirely on JS
  • onclick attributes

Write HTML that works, and then enhance with JS.

If you want to link somewhere: use a link:

<tr>
  <td><a href="http://www.google.com">something</a></td>
  <td>something</td>
</tr>

If you want to make that link work (using JS) for the whole table row, bind an event listener that looks for clicks, and then find the first link in the row that was clicked on.

document.querySelector("table").addEventListener(follow_link_in_row);
function follow_link_in_row(event) {
    var table_row = event.target;
    while (table_row && table_row.tagName.toLowerCase() !== "tr") {
        table_row = table_row.parentNode;
    }
    if (!table_row) { return; }
    var link = table_row.querySelector("a[href]");
    var url = link.href;
    window.location = url;
}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335