Link to home
Start Free TrialLog in
Avatar of Ivan Golubar
Ivan Golubar

asked on

Php syntax: adding onclick event when link is pressed

Next line of code is from x.php:

$note = $log_username.' posted on: <br /><a href="user.php?u='.$account_name.'#status_'.$id.'">'.$account_name.'&#39;s Profile </a>';

Open in new window


and in browser it looks like:  

AAA posted on:
BBB's Profile

What have I  add  in code above to call a function in js script when clicked on href (which is equal to BBB's Profile)?

And how to add this script  on x.php?
ASKER CERTIFIED SOLUTION
Avatar of Ryan Chong
Ryan Chong
Flag of Singapore image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Ivan Golubar
Ivan Golubar

ASKER

Adding an "id" to <a> or to<p>  and then searching for element and assigning click event to it, does not work for me.
@Leonidas Dosas,@Vijaya Kumar

I made  <!DOCTYPE html> with all structure but still no alert or message in console.
(can you check my code below)

@Olaf Doschke
And i don't know how to use just php to do one ajax  request  for $query  for data base update when link is clicked.

<?php
include_once("../php_includes/check_login_status.php");
if($user_ok != true || $log_username == "") {
	exit();
}
?><?php
if (isset($_POST['action']) && $_POST['action'] == "status_post"){
	// Make sure post data is not empty
	if(strlen($_POST['data']) < 1){
		mysqli_close($db_conx);
	    echo "data_empty";
	    exit();
	}
	// Make sure type is either a or c
	if($_POST['type'] != "a" && $_POST['type'] != "c"){
		mysqli_close($db_conx);
	    echo "type_unknown";
	    exit();
	}
	// Clean all of the $_POST vars that will interact with the database
	$type = preg_replace('#[^a-z]#', '', $_POST['type']);
	$account_name = preg_replace('#[^a-z0-9]#i', '', $_POST['user']);
	$data = htmlentities($_POST['data']);
	$data = mysqli_real_escape_string($db_conx, $data);
	// Make sure account name exists (the profile being posted on)
	$sql = "SELECT COUNT(id) FROM users WHERE username='$account_name' AND activated='1' LIMIT 1";
	$query = mysqli_query($db_conx, $sql);
	$row = mysqli_fetch_row($query);
	if($row[0] < 1){
		mysqli_close($db_conx);
		echo "$account_no_exist";
		exit();
	}
	// Insert the status post into the database now
	$sql = "INSERT INTO status(account_name, author, type, data, postdate) 
			VALUES('$account_name','$log_username','$type','$data',now())";
	$query = mysqli_query($db_conx, $sql);
	$id = mysqli_insert_id($db_conx);
	mysqli_query($db_conx, "UPDATE status SET osid='$id' WHERE id='$id' LIMIT 1");
	// Count posts of type "a" for the person posting and evaluate the count
	$sql = "SELECT COUNT(id) FROM status WHERE author='$log_username' AND type='a'";
    $query = mysqli_query($db_conx, $sql); 
	$row = mysqli_fetch_row($query);
	if ($row[0] > 9) { // If they have 10 or more posts of type a
		// Delete their oldest post if you want a system that auto flushes the oldest
		// (you can auto flush for post types c and b if you wish to also)
		$sql = "SELECT id FROM status WHERE author='$log_username' AND type='a' ORDER BY id ASC LIMIT 1";
    	$query = mysqli_query($db_conx, $sql); 
		$row = mysqli_fetch_row($query);
		$oldest = $row[0];
		mysqli_query($db_conx, "DELETE FROM status WHERE osid='$oldest'");
	}
	// Insert notifications to all friends of the post author
	$friends = array();
	$query = mysqli_query($db_conx, "SELECT user1 FROM friends WHERE user2='$log_username' AND accepted='1'");
	while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) { array_push($friends, $row["user1"]); }
	$query = mysqli_query($db_conx, "SELECT user2 FROM friends WHERE user1='$log_username' AND accepted='1'");
	while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) { array_push($friends, $row["user2"]); }
	for($i = 0; $i < count($friends); $i++){
		$friend = $friends[$i];
		$app = "Status Post";
		$note = $log_username.' posted on: <br /><a id="anchorElm" href="user.php?u='.$account_name.'#status_'.$id.'" >'.$account_name.'&#39;s Profile</a>';//
		mysqli_query($db_conx, "INSERT INTO notifications(username, initiator, app, note, date_time) VALUES('$friend','$log_username','$app','$note',now())");			
	}
	mysqli_close($db_conx);
	echo "post_ok|$id";
	exit();
}
?><?php 
//action=status_reply&osid="+osid+"&user="+user+"&data="+data
if (isset($_POST['action']) && $_POST['action'] == "status_reply"){
	// Make sure data is not empty
	if(strlen($_POST['data']) < 1){
		mysqli_close($db_conx);
	    echo "data_empty";
	    exit();
	}
	// Clean the posted variables
	$osid = preg_replace('#[^0-9]#', '', $_POST['sid']);
	$account_name = preg_replace('#[^a-z0-9]#i', '', $_POST['user']);
	$data = htmlentities($_POST['data']);
	$data = mysqli_real_escape_string($db_conx, $data);
	// Make sure account name exists (the profile being posted on)
	$sql = "SELECT COUNT(id) FROM users WHERE username='$account_name' AND activated='1' LIMIT 1";
	$query = mysqli_query($db_conx, $sql);
	$row = mysqli_fetch_row($query);
	if($row[0] < 1){
		mysqli_close($db_conx);
		echo "$account_no_exist";
		exit();
	}
	// Insert the status reply post into the database now
	$sql = "INSERT INTO status(osid, account_name, author, type, data, postdate)
	        VALUES('$osid','$account_name','$log_username','b','$data',now())";
	$query = mysqli_query($db_conx, $sql);
	$id = mysqli_insert_id($db_conx);
	// Insert notifications for everybody in the conversation except this author
	$sql = "SELECT author FROM status WHERE osid='$osid' AND author!='$log_username' GROUP BY author";
	$query = mysqli_query($db_conx, $sql);
	while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
		$participant = $row["author"];
		$app = "Status Reply";
		$note = $log_username.' commented here:<br /><a id="anchorElm" href="user.php?u='.$account_name.'#status_'.$osid.'">Click here to view the conversation</a>';//
		mysqli_query($db_conx, "INSERT INTO notifications(username, initiator, app, note, date_time) 
		             VALUES('$participant','$log_username','$app','$note',now())");
	}
	mysqli_close($db_conx);
	echo "reply_ok|$id";
	exit();
}
?><?php 
if (isset($_POST['action']) && $_POST['action'] == "delete_status"){
	if(!isset($_POST['statusid']) || $_POST['statusid'] == ""){
		mysqli_close($db_conx);
		echo "status id is missing";
		exit();
	}
	$statusid = preg_replace('#[^0-9]#', '', $_POST['statusid']);
	// Check to make sure this logged in user actually owns that comment
	$query = mysqli_query($db_conx, "SELECT account_name, author FROM status WHERE id='$statusid' LIMIT 1");
	while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
		$account_name = $row["account_name"]; 
		$author = $row["author"];
	}
    if ($author == $log_username || $account_name == $log_username) {
		mysqli_query($db_conx, "DELETE FROM status WHERE osid='$statusid'");
		mysqli_close($db_conx);
	    echo "delete_ok";
		exit();
	}
}
?><?php 
if (isset($_POST['action']) && $_POST['action'] == "delete_reply"){
	if(!isset($_POST['replyid']) || $_POST['replyid'] == ""){
		mysqli_close($db_conx);
		exit();
	}
	$replyid = preg_replace('#[^0-9]#', '', $_POST['replyid']);
	// Check to make sure the person deleting this reply is either the account owner or the person who wrote it
	$query = mysqli_query($db_conx, "SELECT osid, account_name, author FROM status WHERE id='$replyid' LIMIT 1");
	while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
		$osid = $row["osid"];
		$account_name = $row["account_name"];
		$author = $row["author"];
	}
    if ($author == $log_username || $account_name == $log_username) {
		mysqli_query($db_conx, "DELETE FROM status WHERE id='$replyid'");
		mysqli_close($db_conx);
	    echo "delete_ok";
		exit();
	}
}
?>

<!DOCTYPE html>
<html>
<head>
<title>HTML, CSS and JavaScript demo</title>
</head>
<body>

  <script>
    document.getElementById('anchorElm').addEventListener('click',function(){
console.log("some");
//code here...
});
    
  </script>
</body>
</html>

Open in new window

Check  in line 62 and 103, pleas.
And i don't know how to use just php to do one ajax  request  for $query  for data base update when link is clicked.
You don't know how to make a SQL qery in PHP? Your code just shows that.

A link causes it's href to be the new page. if you instead want to make an ajax call and stay on the page, then don't use a link, Vijaya Kumar showed how to use a paragraph with onclick event.

If you mean what is similar to an ajax call of some secondary php script within PHP, thatcould simply be include or require other.php. You're already in the PHP server side script, you can do a query there, there is no magic in there.

Bye, Olaf.
The reason that the id attr not working with your JQuery code is because you produce multiple anchor elements with the same id attr. For this case you must use class attr something like this:
<!DOCTYPE html>
<html>
<head>
<title>HTML, CSS and JavaScript demo</title>
</head>
<body>
<!-- Start your code here -->

  <a href="" class="anchorElm">Click Elm 1</a>
  <a href="" class="anchorElm">Click Elm 2</a>
  <a href="" class="anchorElm">Click Elm 2</a>

<!-- End your code here -->
  <script>
    var anchorElm=document.getElementsByClassName('anchorElm');

for(var i=0;i<anchorElm.length;i++){
  anchorElm[i].addEventListener('click',function(){
    console.log(this.innerHTML);
  });
}
  </script>
</body>
</html>

Open in new window


Or with JQuery script
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-latest.min.js"></script>
<title>HTML, CSS and JavaScript demo</title>
</head>
<body>
<!-- Start your code here -->

  <a href="" class="anchorElm">Click Elm 1</a>
  <a href="" class="anchorElm">Click Elm 2</a>
  <a href="" class="anchorElm">Click Elm 2</a>

<!-- End your code here -->
  <script>
    $('.anchorElm').on('click',function(e){
    console.log($(this).text());
    e.preventDefault();
 
});
  </script>
</body>
</html>

Open in new window

multiple id's cannot bind javascript, instead id @Leonidas Dosas uses class was correct solution

and also PHP rendered element use JQUERY like

$(document).on('click','.anchorElm',function(){
  console.log($(this).attr(href));
});

Open in new window



we cannot do ajax calls in php simple navigate using header()
@Leonidas Dosas
Still i do not get alert message.  Pleas, can you check what  em i missing?

<?php
include_once("../php_includes/check_login_status.php");
if($user_ok != true || $log_username == "") {
	exit();
}
?><?php
if (isset($_POST['action']) && $_POST['action'] == "status_post"){
	// Make sure post data is not empty
	if(strlen($_POST['data']) < 1){
		mysqli_close($db_conx);
	    echo "data_empty";
	    exit();
	}
	// Make sure type is either a or c
	if($_POST['type'] != "a" && $_POST['type'] != "c"){
		mysqli_close($db_conx);
	    echo "type_unknown";
	    exit();
	}
	// Clean all of the $_POST vars that will interact with the database
	$type = preg_replace('#[^a-z]#', '', $_POST['type']);
	$account_name = preg_replace('#[^a-z0-9]#i', '', $_POST['user']);
	$data = htmlentities($_POST['data']);
	$data = mysqli_real_escape_string($db_conx, $data);
	// Make sure account name exists (the profile being posted on)
	$sql = "SELECT COUNT(id) FROM users WHERE username='$account_name' AND activated='1' LIMIT 1";
	$query = mysqli_query($db_conx, $sql);
	$row = mysqli_fetch_row($query);
	if($row[0] < 1){
		mysqli_close($db_conx);
		echo "$account_no_exist";
		exit();
	}
	// Insert the status post into the database now
	$sql = "INSERT INTO status(account_name, author, type, data, postdate) 
			VALUES('$account_name','$log_username','$type','$data',now())";
	$query = mysqli_query($db_conx, $sql);
	$id = mysqli_insert_id($db_conx);
	mysqli_query($db_conx, "UPDATE status SET osid='$id' WHERE id='$id' LIMIT 1");
	// Count posts of type "a" for the person posting and evaluate the count
	$sql = "SELECT COUNT(id) FROM status WHERE author='$log_username' AND type='a'";
    $query = mysqli_query($db_conx, $sql); 
	$row = mysqli_fetch_row($query);
	if ($row[0] > 9) { // If they have 10 or more posts of type a
		// Delete their oldest post if you want a system that auto flushes the oldest
		// (you can auto flush for post types c and b if you wish to also)
		$sql = "SELECT id FROM status WHERE author='$log_username' AND type='a' ORDER BY id ASC LIMIT 1";
    	$query = mysqli_query($db_conx, $sql); 
		$row = mysqli_fetch_row($query);
		$oldest = $row[0];
		mysqli_query($db_conx, "DELETE FROM status WHERE osid='$oldest'");
	}
	// Insert notifications to all friends of the post author
	$friends = array();
	$query = mysqli_query($db_conx, "SELECT user1 FROM friends WHERE user2='$log_username' AND accepted='1'");
	while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) { array_push($friends, $row["user1"]); }
	$query = mysqli_query($db_conx, "SELECT user2 FROM friends WHERE user1='$log_username' AND accepted='1'");
	while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) { array_push($friends, $row["user2"]); }
	for($i = 0; $i < count($friends); $i++){
		$friend = $friends[$i];
		$app = "Status Post";
		$note = $log_username.' posted on: <br /><a class="anchorElm" href="user.php?u='.$account_name.'#status_'.$id.'" >'.$account_name.'&#39;s Profile</a>';//
		mysqli_query($db_conx, "INSERT INTO notifications(username, initiator, app, note, date_time) VALUES('$friend','$log_username','$app','$note',now())");			
	}
	mysqli_close($db_conx);
	echo "post_ok|$id";
	exit();
}
?><?php 
//action=status_reply&osid="+osid+"&user="+user+"&data="+data
if (isset($_POST['action']) && $_POST['action'] == "status_reply"){
	// Make sure data is not empty
	if(strlen($_POST['data']) < 1){
		mysqli_close($db_conx);
	    echo "data_empty";
	    exit();
	}
	// Clean the posted variables
	$osid = preg_replace('#[^0-9]#', '', $_POST['sid']);
	$account_name = preg_replace('#[^a-z0-9]#i', '', $_POST['user']);
	$data = htmlentities($_POST['data']);
	$data = mysqli_real_escape_string($db_conx, $data);
	// Make sure account name exists (the profile being posted on)
	$sql = "SELECT COUNT(id) FROM users WHERE username='$account_name' AND activated='1' LIMIT 1";
	$query = mysqli_query($db_conx, $sql);
	$row = mysqli_fetch_row($query);
	if($row[0] < 1){
		mysqli_close($db_conx);
		echo "$account_no_exist";
		exit();
	}
	// Insert the status reply post into the database now
	$sql = "INSERT INTO status(osid, account_name, author, type, data, postdate)
	        VALUES('$osid','$account_name','$log_username','b','$data',now())";
	$query = mysqli_query($db_conx, $sql);
	$id = mysqli_insert_id($db_conx);
	// Insert notifications for everybody in the conversation except this author
	$sql = "SELECT author FROM status WHERE osid='$osid' AND author!='$log_username' GROUP BY author";
	$query = mysqli_query($db_conx, $sql);
	while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
		$participant = $row["author"];
		$app = "Status Reply";
		$note = $log_username.' commented here:<br /><a class="anchorElm" href="user.php?u='.$account_name.'#status_'.$osid.'">Click here to view the conversation</a>';//
		mysqli_query($db_conx, "INSERT INTO notifications(username, initiator, app, note, date_time) 
		             VALUES('$participant','$log_username','$app','$note',now())");
	}
	mysqli_close($db_conx);
	echo "reply_ok|$id";
	exit();
}
?><?php 
if (isset($_POST['action']) && $_POST['action'] == "delete_status"){
	if(!isset($_POST['statusid']) || $_POST['statusid'] == ""){
		mysqli_close($db_conx);
		echo "status id is missing";
		exit();
	}
	$statusid = preg_replace('#[^0-9]#', '', $_POST['statusid']);
	// Check to make sure this logged in user actually owns that comment
	$query = mysqli_query($db_conx, "SELECT account_name, author FROM status WHERE id='$statusid' LIMIT 1");
	while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
		$account_name = $row["account_name"]; 
		$author = $row["author"];
	}
    if ($author == $log_username || $account_name == $log_username) {
		mysqli_query($db_conx, "DELETE FROM status WHERE osid='$statusid'");
		mysqli_close($db_conx);
	    echo "delete_ok";
		exit();
	}
}
?><?php 
if (isset($_POST['action']) && $_POST['action'] == "delete_reply"){
	if(!isset($_POST['replyid']) || $_POST['replyid'] == ""){
		mysqli_close($db_conx);
		exit();
	}
	$replyid = preg_replace('#[^0-9]#', '', $_POST['replyid']);
	// Check to make sure the person deleting this reply is either the account owner or the person who wrote it
	$query = mysqli_query($db_conx, "SELECT osid, account_name, author FROM status WHERE id='$replyid' LIMIT 1");
	while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
		$osid = $row["osid"];
		$account_name = $row["account_name"];
		$author = $row["author"];
	}
    if ($author == $log_username || $account_name == $log_username) {
		mysqli_query($db_conx, "DELETE FROM status WHERE id='$replyid'");
		mysqli_close($db_conx);
	    echo "delete_ok";
		exit();
	}
}
?>

<!DOCTYPE html>
<html>
<head>
<title>HTML, CSS and JavaScript demo</title>
</head>
<body>

  <script>
   var anchorElm=document.getElementsByClassName('anchorElm');

for(var i=0;i<anchorElm.length;i++){
  anchorElm[i].addEventListener('click',function(){
    console.log("11111111111111");
    alert("11111111111111");
  });
} 
  </script>
</body>
</html>

Open in new window

@Olaf Doschke
I need to follow the link.
How to make next in php?
(next code snippets are from code in previous link)


When i click on next link:
$note = $log_username.' posted on: <br /><a class="anchorElm" href="user.php?u='.$account_name.'#status_'.$id.'" >'.$account_name.'&#39;s Profile</a>';//

Open in new window


or on next link:
      
$note = $log_username.' commented here:<br /><a class="anchorElm" href="user.php?u='.$account_name.'#status_'.$osid.'">Click here to view the conversation</a>';//

Open in new window


I need next to perform:
   
  $sql = "UPDATE notifications SET did_read='1' WHERE id='$noteid' LIMIT 1";//AND id='$rowID'

Open in new window

Check this script.I removed the piece of the php code that producing anchor elements inside the bode element.If the js script find anchor elements alert a message.
!<?php
include_once("../php_includes/check_login_status.php");
if($user_ok != true || $log_username == "") {
	exit();
}
?><?php
if (isset($_POST['action']) && $_POST['action'] == "status_post"){
	// Make sure post data is not empty
	if(strlen($_POST['data']) < 1){
		mysqli_close($db_conx);
	    echo "data_empty";
	    exit();
	}
	// Make sure type is either a or c
	if($_POST['type'] != "a" && $_POST['type'] != "c"){
		mysqli_close($db_conx);
	    echo "type_unknown";
	    exit();
	}
	// Clean all of the $_POST vars that will interact with the database
	$type = preg_replace('#[^a-z]#', '', $_POST['type']);
	$account_name = preg_replace('#[^a-z0-9]#i', '', $_POST['user']);
	$data = htmlentities($_POST['data']);
	$data = mysqli_real_escape_string($db_conx, $data);
	// Make sure account name exists (the profile being posted on)
	$sql = "SELECT COUNT(id) FROM users WHERE username='$account_name' AND activated='1' LIMIT 1";
	$query = mysqli_query($db_conx, $sql);
	$row = mysqli_fetch_row($query);
	if($row[0] < 1){
		mysqli_close($db_conx);
		echo "$account_no_exist";
		exit();
	}
	// Insert the status post into the database now
	$sql = "INSERT INTO status(account_name, author, type, data, postdate) 
			VALUES('$account_name','$log_username','$type','$data',now())";
	$query = mysqli_query($db_conx, $sql);
	$id = mysqli_insert_id($db_conx);
	mysqli_query($db_conx, "UPDATE status SET osid='$id' WHERE id='$id' LIMIT 1");
	// Count posts of type "a" for the person posting and evaluate the count
	$sql = "SELECT COUNT(id) FROM status WHERE author='$log_username' AND type='a'";
    $query = mysqli_query($db_conx, $sql); 
	$row = mysqli_fetch_row($query);
	if ($row[0] > 9) { // If they have 10 or more posts of type a
		// Delete their oldest post if you want a system that auto flushes the oldest
		// (you can auto flush for post types c and b if you wish to also)
		$sql = "SELECT id FROM status WHERE author='$log_username' AND type='a' ORDER BY id ASC LIMIT 1";
    	$query = mysqli_query($db_conx, $sql); 
		$row = mysqli_fetch_row($query);
		$oldest = $row[0];
		mysqli_query($db_conx, "DELETE FROM status WHERE osid='$oldest'");
	}
	// Insert notifications to all friends of the post author

?><?php 
//action=status_reply&osid="+osid+"&user="+user+"&data="+data
if (isset($_POST['action']) && $_POST['action'] == "status_reply"){
	// Make sure data is not empty
	if(strlen($_POST['data']) < 1){
		mysqli_close($db_conx);
	    echo "data_empty";
	    exit();
	}
	// Clean the posted variables
	$osid = preg_replace('#[^0-9]#', '', $_POST['sid']);
	$account_name = preg_replace('#[^a-z0-9]#i', '', $_POST['user']);
	$data = htmlentities($_POST['data']);
	$data = mysqli_real_escape_string($db_conx, $data);
	// Make sure account name exists (the profile being posted on)
	$sql = "SELECT COUNT(id) FROM users WHERE username='$account_name' AND activated='1' LIMIT 1";
	$query = mysqli_query($db_conx, $sql);
	$row = mysqli_fetch_row($query);
	if($row[0] < 1){
		mysqli_close($db_conx);
		echo "$account_no_exist";
		exit();
	}
	// Insert the status reply post into the database now
	$sql = "INSERT INTO status(osid, account_name, author, type, data, postdate)
	        VALUES('$osid','$account_name','$log_username','b','$data',now())";
	$query = mysqli_query($db_conx, $sql);
	$id = mysqli_insert_id($db_conx);
	// Insert notifications for everybody in the conversation except this author
	$sql = "SELECT author FROM status WHERE osid='$osid' AND author!='$log_username' GROUP BY author";
	$query = mysqli_query($db_conx, $sql);
	while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
		$participant = $row["author"];
		$app = "Status Reply";
		$note = $log_username.' commented here:<br /><a class="anchorElm" href="user.php?u='.$account_name.'#status_'.$osid.'">Click here to view the conversation</a>';//
		mysqli_query($db_conx, "INSERT INTO notifications(username, initiator, app, note, date_time) 
		             VALUES('$participant','$log_username','$app','$note',now())");
	}
	mysqli_close($db_conx);
	echo "reply_ok|$id";
	exit();
}
?><?php 
if (isset($_POST['action']) && $_POST['action'] == "delete_status"){
	if(!isset($_POST['statusid']) || $_POST['statusid'] == ""){
		mysqli_close($db_conx);
		echo "status id is missing";
		exit();
	}
	$statusid = preg_replace('#[^0-9]#', '', $_POST['statusid']);
	// Check to make sure this logged in user actually owns that comment
	$query = mysqli_query($db_conx, "SELECT account_name, author FROM status WHERE id='$statusid' LIMIT 1");
	while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
		$account_name = $row["account_name"]; 
		$author = $row["author"];
	}
    if ($author == $log_username || $account_name == $log_username) {
		mysqli_query($db_conx, "DELETE FROM status WHERE osid='$statusid'");
		mysqli_close($db_conx);
	    echo "delete_ok";
		exit();
	}
}
?><?php 
if (isset($_POST['action']) && $_POST['action'] == "delete_reply"){
	if(!isset($_POST['replyid']) || $_POST['replyid'] == ""){
		mysqli_close($db_conx);
		exit();
	}
	$replyid = preg_replace('#[^0-9]#', '', $_POST['replyid']);
	// Check to make sure the person deleting this reply is either the account owner or the person who wrote it
	$query = mysqli_query($db_conx, "SELECT osid, account_name, author FROM status WHERE id='$replyid' LIMIT 1");
	while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
		$osid = $row["osid"];
		$account_name = $row["account_name"];
		$author = $row["author"];
	}
    if ($author == $log_username || $account_name == $log_username) {
		mysqli_query($db_conx, "DELETE FROM status WHERE id='$replyid'");
		mysqli_close($db_conx);
	    echo "delete_ok";
		exit();
	}
}
?>

<!DOCTYPE html>
<html>
<head>
<title>HTML, CSS and JavaScript demo</title>
</head>
<body>
<?php
	$friends = array();
	$query = mysqli_query($db_conx, "SELECT user1 FROM friends WHERE user2='$log_username' AND accepted='1'");
	while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) { array_push($friends, $row["user1"]); }
	$query = mysqli_query($db_conx, "SELECT user2 FROM friends WHERE user1='$log_username' AND accepted='1'");
	while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) { array_push($friends, $row["user2"]); }
	for($i = 0; $i < count($friends); $i++){
		$friend = $friends[$i];
		$app = "Status Post";
		$note = $log_username.' posted on: <br /><a class="anchorElm" href="user.php?u='.$account_name.'#status_'.$id.'" >'.$account_name.'&#39;s Profile</a>';//
		mysqli_query($db_conx, "INSERT INTO notifications(username, initiator, app, note, date_time) VALUES('$friend','$log_username','$app','$note',now())");			
	}
	mysqli_close($db_conx);
	echo "post_ok|$id";
	exit();
}
?>
  <script>
   var anchorElm=document.getElementsByClassName('anchorElm');
  if(anchorElm){
      alert('anchor elements exist');
  }else{
    alert('anchor NOT elements exist') ; 
  }
for(var i=0;i<anchorElm.length;i++){
  anchorElm[i].addEventListener('click',function(){
    console.log("11111111111111");
    alert("11111111111111");
  });
} 
  </script>
</body>
</html>

Open in new window

I did  also try next but still no success.

<script>
  alert("22222222");
   console.log("11111111111111");

Open in new window


<?php
include_once("../php_includes/check_login_status.php");
if($user_ok != true || $log_username == "") {
	exit();
}
?><?php
if (isset($_POST['action']) && $_POST['action'] == "status_post"){
	// Make sure post data is not empty
	if(strlen($_POST['data']) < 1){
		mysqli_close($db_conx);
	    echo "data_empty";
	    exit();
	}
	// Make sure type is either a or c
	if($_POST['type'] != "a" && $_POST['type'] != "c"){
		mysqli_close($db_conx);
	    echo "type_unknown";
	    exit();
	}
	// Clean all of the $_POST vars that will interact with the database
	$type = preg_replace('#[^a-z]#', '', $_POST['type']);
	$account_name = preg_replace('#[^a-z0-9]#i', '', $_POST['user']);
	$data = htmlentities($_POST['data']);
	$data = mysqli_real_escape_string($db_conx, $data);
	// Make sure account name exists (the profile being posted on)
	$sql = "SELECT COUNT(id) FROM users WHERE username='$account_name' AND activated='1' LIMIT 1";
	$query = mysqli_query($db_conx, $sql);
	$row = mysqli_fetch_row($query);
	if($row[0] < 1){
		mysqli_close($db_conx);
		echo "$account_no_exist";
		exit();
	}
	// Insert the status post into the database now
	$sql = "INSERT INTO status(account_name, author, type, data, postdate) 
			VALUES('$account_name','$log_username','$type','$data',now())";
	$query = mysqli_query($db_conx, $sql);
	$id = mysqli_insert_id($db_conx);
	mysqli_query($db_conx, "UPDATE status SET osid='$id' WHERE id='$id' LIMIT 1");
	// Count posts of type "a" for the person posting and evaluate the count
	$sql = "SELECT COUNT(id) FROM status WHERE author='$log_username' AND type='a'";
    $query = mysqli_query($db_conx, $sql); 
	$row = mysqli_fetch_row($query);
	if ($row[0] > 9) { // If they have 10 or more posts of type a
		// Delete their oldest post if you want a system that auto flushes the oldest
		// (you can auto flush for post types c and b if you wish to also)
		$sql = "SELECT id FROM status WHERE author='$log_username' AND type='a' ORDER BY id ASC LIMIT 1";
    	$query = mysqli_query($db_conx, $sql); 
		$row = mysqli_fetch_row($query);
		$oldest = $row[0];
		mysqli_query($db_conx, "DELETE FROM status WHERE osid='$oldest'");
	}
	// Insert notifications to all friends of the post author
	$friends = array();
	$query = mysqli_query($db_conx, "SELECT user1 FROM friends WHERE user2='$log_username' AND accepted='1'");
	while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) { array_push($friends, $row["user1"]); }
	$query = mysqli_query($db_conx, "SELECT user2 FROM friends WHERE user1='$log_username' AND accepted='1'");
	while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) { array_push($friends, $row["user2"]); }
	for($i = 0; $i < count($friends); $i++){
		$friend = $friends[$i];
		$app = "Status Post";
		$note = $log_username.' posted on: <br /><a class="anchorElm" href="user.php?u='.$account_name.'#status_'.$id.'" >'.$account_name.'&#39;s Profile</a>';//
		mysqli_query($db_conx, "INSERT INTO notifications(username, initiator, app, note, date_time) VALUES('$friend','$log_username','$app','$note',now())");			
	}
	mysqli_close($db_conx);
	echo "post_ok|$id";
	exit();
}
?><?php 
//action=status_reply&osid="+osid+"&user="+user+"&data="+data
if (isset($_POST['action']) && $_POST['action'] == "status_reply"){
	// Make sure data is not empty
	if(strlen($_POST['data']) < 1){
		mysqli_close($db_conx);
	    echo "data_empty";
	    exit();
	}
	// Clean the posted variables
	$osid = preg_replace('#[^0-9]#', '', $_POST['sid']);
	$account_name = preg_replace('#[^a-z0-9]#i', '', $_POST['user']);
	$data = htmlentities($_POST['data']);
	$data = mysqli_real_escape_string($db_conx, $data);
	// Make sure account name exists (the profile being posted on)
	$sql = "SELECT COUNT(id) FROM users WHERE username='$account_name' AND activated='1' LIMIT 1";
	$query = mysqli_query($db_conx, $sql);
	$row = mysqli_fetch_row($query);
	if($row[0] < 1){
		mysqli_close($db_conx);
		echo "$account_no_exist";
		exit();
	}
	// Insert the status reply post into the database now
	$sql = "INSERT INTO status(osid, account_name, author, type, data, postdate)
	        VALUES('$osid','$account_name','$log_username','b','$data',now())";
	$query = mysqli_query($db_conx, $sql);
	$id = mysqli_insert_id($db_conx);
	// Insert notifications for everybody in the conversation except this author
	$sql = "SELECT author FROM status WHERE osid='$osid' AND author!='$log_username' GROUP BY author";
	$query = mysqli_query($db_conx, $sql);
	while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
		$participant = $row["author"];
		$app = "Status Reply";
		$note = $log_username.' commented here:<br /><a class="anchorElm" href="user.php?u='.$account_name.'#status_'.$osid.'">Click here to view the conversation</a>';//
		mysqli_query($db_conx, "INSERT INTO notifications(username, initiator, app, note, date_time) 
		             VALUES('$participant','$log_username','$app','$note',now())");
	}
	mysqli_close($db_conx);
	echo "reply_ok|$id";
	exit();
}
?><?php 
if (isset($_POST['action']) && $_POST['action'] == "delete_status"){
	if(!isset($_POST['statusid']) || $_POST['statusid'] == ""){
		mysqli_close($db_conx);
		echo "status id is missing";
		exit();
	}
	$statusid = preg_replace('#[^0-9]#', '', $_POST['statusid']);
	// Check to make sure this logged in user actually owns that comment
	$query = mysqli_query($db_conx, "SELECT account_name, author FROM status WHERE id='$statusid' LIMIT 1");
	while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
		$account_name = $row["account_name"]; 
		$author = $row["author"];
	}
    if ($author == $log_username || $account_name == $log_username) {
		mysqli_query($db_conx, "DELETE FROM status WHERE osid='$statusid'");
		mysqli_close($db_conx);
	    echo "delete_ok";
		exit();
	}
}
?>

<!DOCTYPE html>
<html>
<head>
<title>HTML, CSS and JavaScript demo</title>
</head>
<body>

<?php 
if (isset($_POST['action']) && $_POST['action'] == "delete_reply"){
	if(!isset($_POST['replyid']) || $_POST['replyid'] == ""){
		mysqli_close($db_conx);
		exit();
	}
	$replyid = preg_replace('#[^0-9]#', '', $_POST['replyid']);
	// Check to make sure the person deleting this reply is either the account owner or the person who wrote it
	$query = mysqli_query($db_conx, "SELECT osid, account_name, author FROM status WHERE id='$replyid' LIMIT 1");
	while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
		$osid = $row["osid"];
		$account_name = $row["account_name"];
		$author = $row["author"];
	}
    if ($author == $log_username || $account_name == $log_username) {
		mysqli_query($db_conx, "DELETE FROM status WHERE id='$replyid'");
		mysqli_close($db_conx);
	    echo "delete_ok";
		exit();
	}
}
?>

  <script>
  alert("22222222");
   console.log("11111111111111");
   var anchorElm=document.getElementsByClassName('anchorElm');
for(var i=0;i<anchorElm.length;i++){
  anchorElm[i].addEventListener('click',function(){
    console.log("11111111111111");
    alert("11111111111111");
  });
} 
  </script>
</body>
</html>

Open in new window

Run this javascript tester to see if the javascript is enabled  Javascript tester
it says that JS works.
Nowhere you have echo the anchor elements so the js code didn't find them. Could you post an image of the browser screen and a second image with your console outputs?
Nowhere you have echo the anchor elements so the js code didn't find them.

What have i to change  in my code about ?
Untitled2.png
To call an event function as you wrote at the beginning of this post you must some where produce the anchor elements like this:
php code:
echo '<a href="user.php?u='.$account_name.'#status_'.$id.'">'.$account_name.'&#39;s Profile </a>'

Open in new window

The console said that the javascript code doesn't find these elements.
Can you show it in my code, pleas?
>I need to follow the link.

You overlook what Vijaya Kumar gave you as the solution to that problem..
1. the p tag calls JS via onclick event.
2. the JS script at its end does either an ajax request or simply sets window.location.href to the target URL.

You can't have both at the same time with a link, so you "emulate" a link redirected through JS. If that's what you need at all. I'm still quite sure all you need is to extend your user.php script and your Js frontend doesn't have to be involved at all.

What do you actually want to do with JS? JS typically is updating the current page in some manner, manipulating the DOM. But once you request a PHP script with a normal link, you replace the whole current page with something new. So the only other thing a JS script may do just before leaving the current page is making an ajax call aside and just before navigating to the target URL. And that means making another server-side request. And PHP can do that, too. So I don't even see the need to fork into two actions here.

If you do what you do, because you can't change user.php, create a new php script, let the link go through that and let it require/include user.php or redirect to it, after you did whatever extra action.

Bye, Olaf.
Thank you

I will start now to study you replay.
@Olaf Doschke
about point 1.

Next is the result difference. If i use <p> i lose the link.

Check attached picture.

I am going on now to study your replay.
Let me understand all before taking any action.
Untitled5.png
That a paragraph doesn't look like a link is the least problem, style it with CSS.

And my own recommendation is staying with a link and just extending user.php for all you want to do or create a new php script, whoch at it'send redirects to user.php

In any case you can do whatever you need to do, there's no need to show that.

Bye, Olaf.
I did delete my previous post because i made a mistake. I am really sorry. But i will redo it in a moment.
I am  thinking to as first illustrate what actually code does and then I will explain what is my goal.

Next is part from status_system.php.  which writes data in DB
	// Insert notifications to all friends of the post author
	$friends = array();
	$query = mysqli_query($db_conx, "SELECT user1 FROM friends WHERE user2='$log_username' AND accepted='1'");
	while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) { array_push($friends, $row["user1"]); }
	$query = mysqli_query($db_conx, "SELECT user2 FROM friends WHERE user1='$log_username' AND accepted='1'");
	while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) { array_push($friends, $row["user2"]); }
	for($i = 0; $i < count($friends); $i++){
		$friend = $friends[$i];
		$app = "Status Post";
              $note = $log_username.' posted on: <br /><p href="user.php?u='.$account_name.'#status_'.$id.'" >'.$account_name.'&#39;s Profile</p>';
		mysqli_query($db_conx, "INSERT INTO notifications(username, initiator, app, note, date_time) VALUES('$friend','$log_username','$app','$note',now())");			
	}

Open in new window


Then with next code notifications.php i am getting the view  which i have posted  on attached picture in last post.
$notification_list = "";
$sql = "SELECT * FROM notifications WHERE username LIKE BINARY '$log_username' AND did_read='0' ORDER BY date_time DESC";
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
if($numrows < 1){
	$notification_list = "You do not have any notifications";
} else {
	while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
		$noteid = $row["id"];
		$initiator = $row["initiator"];
		$app = $row["app"];
		$note = $row["note"];
		$date_time = $row["date_time"];
		$date_time = strftime("%b %d, %Y", strtotime($date_time));
		$notification_list .= "<p><a href='user.php?u=$initiator'>$initiator</a> | $app<br />$note</p>";
	  
	}
}

Open in new window

I don't know why you're posting that. When you want to call these script, then do so.

Eg change link to mynew.php with the same parameterization, then in that PHP simply do

mynew.php:
require status_system.php;
require notifications.php;
require user.php;

Open in new window


And you have all three called with one click. You might do

alternative mynew.php
require status_system.php;
require notifications.php;
header('Location:user.php?'. $_SERVER['QUERY_STRING']);

Open in new window


That needs status_system.php and notifications.php to absolutely have no echo or other output, but as you describe them, they only do some mysql queries. The difference is, the browser will now show the user.php URL as current url instead of mynew.php

Bye, Olaf.
Before i did attach working exisisting code.
Now I want to expand it to option
when the link in third line of attached picture is pressed  is been noticed, so it will no longer be present in notification list on page refresh.
That's why ia am adding  Did_read variable (which was not there from the begging) to notification.php in line:
$sql = "SELECT * FROM notifications WHERE username LIKE BINARY '$log_username' AND did_read='0' ORDER BY date_time DESC";

Open in new window

I am not sure if it is a good approach. But i would  not like to change my exiting code, but reader add optional code.
Can You help me with this,pleas?

What  i need now is code  which will set "Did_read" to value "1"
I would like to use :onclick='return updateDid_read($noteid);' in next line of notification.php
$notification_list .= "<p><a href='user.php?u=$initiator' onclick='return updateDid_read($noteid);'>$initiator</a> | $app<br />$note</p>";

Open in new window


with:
function updateDid_read(noteid){
$.ajax({
  method:"POST",
  url: '/wp-content/themes/aaa/bbb/notification.php',
  data:  {
      "ifUpdateDid_read":1,
      "noteID":noteID
   },
   datatype: "text",
  success: function(strdate){
           console.log("111");
         
     },
     error: function(error, txtStatus) {
      console.log(txtStatus);
      console.log('error');
    }
  });
}

Open in new window


And then in notification.php to perform Query:
<?php 
   if (isset($_POST["ifUpdateDid_read"]) ) { 
      $rowID= mysqli_real_escape_string($db_conx, $_POST['noteID']);
     $sql = "UPDATE notifications SET did_read='1' WHERE id='$rowID' LIMIT 1";//AND 
     $query = mysqli_query($db_conx, $sql);
       }
?>

Open in new window


To recapitulate:
What  i need now is code  which will set "Did_read" to value "1" when link in third line of attached picture is pressed.
How to do it?
ivans.jpg
What  i need now is code  which will set "Did_read" to value "1"
I would like to use :onclick='return updateDid_read($noteid);' in next line of notification.php
$notification_list .= "<p><a href='user.php?u=$initiator' onclick='return updateDid_read($noteid);'> $initiator</a>| $app<br />$note</p>";


Above is wrong because is referring  to first line of attached picture (underlined). The link which i have to notice when is pressed is in  ">$note</p>"
and that variable is built in status_system.php  (code line 10.)
Why do you still insist on doing things client side? When the JS code you want to execute makes MySQL queries, it does so by calling PHP scritps, doesn't it?

You don't need to call JS code to make PHP calls, you can do so in PHP, it's even more direct and simpler, and you don't need to cause an onclick event and the link to work, you get rid of this problem.

Change your user.php to instead call another new PHP script. Provide all parameters user.php will need and all necessary information you need for the previous step of updating the "did_read" column in the correct record(s). In the new script, you don't return to your HTML page, you come out with what user.php does as final output, as if the link would call into user.php

You could also still just change user.php to execute that updates you want to do, if new parameters are passed in.

Bye, Olaf.
Thank you for support.

I would like to go step by step. Because is hard for me to understand.

I will need next:
$sql = "UPDATE notifications SET did_read='1' WHERE id='$rowID' LIMIT 1";

Open in new window


Confirm if it is correct.
I can't tell you what SQL you need.  The SQL itself looks valid, it updates1 row, but I can't tell you about your tables, meanings of columns, field types,  etc.

If you don't get an error displayed, but you also don't see the update working, maybe you look into PHP error reporting.

Bye, Olaf.
$sql = "UPDATE notifications SET did_read='1' WHERE id='$rowID' LIMIT 1";

Open in new window


In line above  there is variable $rowID which tells  which row in data base table has to be updated.

The point is  how to get that variable.
Generally you have these variables at hand:
1. $_SESSION
2. $_GET or $_POST
3. $_COOKIE
4. Anything in the current context your script runs in (eg when it is included or required).

So either you know the $rowid or you change your WHERE-clause to something making use of parameters you DO know e.g. username.
And you can add to $_GET in case your call is via the link, you can add to the parameter part of the URL.

Bye, Olaf.
I get  $noteid = $row["id"]; (row 9 of notification.php)
to use in
$sql = "UPDATE notifications SET did_read='1' WHERE id='$noteid' LIMIT 1";
The update of notifications table has to be performed when clicking on link which is "something" inside of $note
(last line notification.php). But $note is built in row 10 of status_system.php .
What does confuse me even more  is that status_system.php is used when first user sends post  and notification.php is used when second user opens his notification  page.
But in this point ,if I follow some  logic, am thinking that here I must add "something" to
<a href="user.php?u='.$account_name.'#status_'.$id.'">'.$account_name.'&#39;s Profile</a>
(row 10  of status_system.php) to perform
$sql = "UPDATE notifications SET did_read='1' WHERE id='$noteid' LIMIT 1";
when  link then in notification.php is clicked.
I need some instructions here?
notification.php
$notification_list = "";
$sql = "SELECT * FROM notifications WHERE username LIKE BINARY '$log_username' AND did_read='0' ORDER BY date_time DESC";
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
if($numrows < 1){
	$notification_list = "You do not have any notifications";
} else {
	while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
		$noteid = $row["id"];
		$initiator = $row["initiator"];
		$app = $row["app"];
		$note = $row["note"];
		$date_time = $row["date_time"];
		$date_time = strftime("%b %d, %Y", strtotime($date_time));
	    $notification_list .= "<p><a href='user.php?u=$initiator'>$initiator</a> | $app<br />$note</p>";	
}

Open in new window


status_system.php
	$friends = array();
	$query = mysqli_query($db_conx, "SELECT user1 FROM friends WHERE user2='$log_username' AND accepted='1'");
	while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) { array_push($friends, $row["user1"]); }
	$query = mysqli_query($db_conx, "SELECT user2 FROM friends WHERE user1='$log_username' AND accepted='1'");
	while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) { array_push($friends, $row["user2"]); }
	for($i = 0; $i < count($friends); $i++){
		$friend = $friends[$i];
		$app = "Status Post";
        $note = $log_username.' posted on: <br /><a href="user.php?u='.$account_name.'#status_'.$id.'">'.$account_name.'&#39;s Profile</a>';
		mysqli_query($db_conx, "INSERT INTO notifications(username, initiator, app, note, date_time) VALUES('$friend','$log_username','$app','$note',now())");			
	}

Open in new window

You have to make clear one basic concept: While you execute PHP only PHP runs, it generates HTML and JS (it can do more, but let's not get distracted), when that is done, all PHP variables also are gone, JS only has access to anything put into the HTML or it's source code. So "keeping a PHP variable available" can mean to put it's value into HTML form elements (hidden), add them as parameter in URLs with a query string or write out JS that defines and sets variables to the same values currently in the PHP variable. And you might even come up with 10 more ideas.

One more simpler is to persist variable values inside session variables or cookies. I already hinted on that being available, too.

Don't expect experts to read through tons of code not even knowing about the used framework, system, database, meanings of fields etc. For me this is at the end of a thread having become far too lengthy already.

It should have become clear a link trying to do two things at the same time isn't a good idea and you either decide to let it run some JS ending in a final PHP call or do all you want to do in PHP with the neccessary data either ping-ponged from PHP to HTML/JS back to PHP or held in session variables or even stored in the backend database.

Bye, Olaf.
Success.

I did next:
To status_system.php  i did add (check underlined):
$note = $log_username.' posted on: <br /><a  href="user.php?u='.$account_name.'#status_'.$id.'" onclick=" return updateDid_read();">'.$account_name.'&#39;s Profile</a>';

To notifications php i did add (check underlined):
$sql = "SELECT * FROM notifications WHERE username LIKE BINARY '$log_username' AND did_read='0' ORDER BY date_time DESC";
and
 $notification_list .= "<p id=$noteid><a  href='user.php?u=$initiator'>$initiator</a> | $app <br />$note</p>";
and all next code snippet:
<?php 
   if (isset($_POST["noteID"]) ) { 
      $noteID= mysqli_real_escape_string($db_conx, $_POST['noteID']);
     $sql = "UPDATE notifications SET did_read='1' WHERE id= '$noteID' LIMIT 1";
     $query = mysqli_query($db_conx, $sql);
       }
?>

Open in new window

and all next code snippet:
function updateDid_read(){
    
var noteID=document.activeElement.parentElement.id;

$.ajax({
  method:"POST",
  url: '/wp-content/themes/n4/n4/notifications.php',
  data:  {
      "noteID":noteID
   },
   datatype: "text",
  success: function(strdate){
     },
     error: function(error, txtStatus) {
      console.log(txtStatus);
      console.log('error');
    }
  });
}

Open in new window

Untitled6.png