0

I have a problem adding events from the javascript to php i echo using ajax.

session_start();
include "objects.php";
include "db.php";
$userId = $_SESSION['userId'];
$userName = $_SESSION['username'];

$html = '<h2 class="peopleHeader divSubContainer" id="peopleFriendsHeader" data-id ="peopleFriendsHeader" 
    data-target="peopleFriends" style="cursor:pointer" onclick=hideShowh2(this.getAttribute("data-id"),this.getAttribute("data-target"))>
    Friends <button id="refreshButton"><i class="fa fa-refresh" style="font-size:24px"></i></button></h2>';
    
$html .= '<ul class="peopleFriends" id="peopleFriends">';
$query = "select * from user_status where userId = " . $userId;
$selectingData = new selectingData($query, $conn);
$result = $selectingData->getResult();
if (count(json_decode($result[0]['friends'])) > 0) {
    foreach ($result as $r) {
        $allFriends = json_decode(strtolower(stripslashes($r['friends'])));
        foreach ($allFriends as $r2) {
            $query = 'select * from chatsystemuser where userName ="' . $r2 . '"';
            $selectingData = new selectingData($query, $conn);
            $result = $selectingData->getResult();
            foreach ($result as $r) {
                $html .= "<li><p>" . $r2 . "</p><button data-target-user= '".$r['id']."' id='friendsMessageButton" . $r['id'] . "' class='btn friendsMessageButton'>MESSAGE
                    </button></li>";
            }
        }
    }
} else {
    $html .= "<h2> NO FRIENDS </h2>";
}
$html .= "</ul>";
echo $html;

This is my javascript ajax thatmake display to the browser.

function displayingFriends() {
    var friends = $('.listOfFriends');
    $.ajax({
        url: "include/friends.php",
        type: 'post',
        datatype: 'html',
        success: function (data) {
            friends.html(data);
        }
    })
}

I try to select all data-target-modal but the closeButton variable is empty

function displayMessageModal() {
    let closeButton = document.querySelectorAll('[data-target-modal]')
    let overlay = document.querySelector('#overlay');
    let friendsMessageButton = document.querySelectorAll('[data-target-user]');

    console.log(closeButton)

    friendsMessageButton.forEach(function (btn) {
        var target = friendsMessageButton.closest('.messages');
        btn.addEventListener('click', function () {
            openDisplay(target);
            console.log('clicked')
        })
    })
    closeButton.forEach(function () {
        var target = closeButton.closest('.messages');
        closeButton.addEventListener('click', function () {
            closeDisplay(target)
        })
    })
    function closeDisplay(target) {
        target.classList.remove('active');
        overlay.classList.remove('active');
    }

    function openDisplay(target) {
        target.classList.add('active');
        overlay.classList.add('active');
    }
}
$(function () {
    displayingFriends()
    displayMessageModal()
})

I want to select all button using data attributes. Sorry for my bad english im not really good at talking in english but i can understand it really well.

  • 2
    So let's assume the AJAX works. Can you click edit, then the button that looks like this `[<>]` - paste pure HTML, script and CSS - NO PHP! - into the panes to make a [mcve] – mplungjan Sep 07 '20 at 06:13
  • Also. You have jQuery, why not USE it instead of mixing DOM and jQuery? You likely just need to delegate, but you have posted too much irrelevant code for me to be sure – mplungjan Sep 07 '20 at 06:15
  • There's no element with `data-target-modal="..."` in your question -> [mcve] – Andreas Sep 07 '20 at 06:16
  • Likely a dupe of https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – mplungjan Sep 07 '20 at 06:17

3 Answers3

0

That is because you are invoking displayMessageModal() at runtime, and not when the promise from AJAX has been resolved. A possible solution will be:

  1. Return the promise from displayingFriends()
  2. Invoke displayMessageModal() after the promise has been resolved

An example:

function displayingFriends() {
    var friends = $('.listOfFriends');

    // Return the promise here
    return $.ajax({
        url: "include/friends.php",
        type: 'post',
        datatype: 'html',
        success: function (data) {
            friends.html(data);
        }
    })
}

Then, you can wait for the promise to be resovled:

$(function () {
    displayingFriends().then(() => displayMessageModal());
});
Terry
  • 63,248
  • 15
  • 96
  • 118
0

In this code you made a little typo here

$html .= "<li><p>" . $r2 . "</p><button data-target-user= '".$r['id']."' id='friendsMessageButton" . $r['id'] . "' class='btn friendsMessageButton'>MESSAGE
                </button></li>";

In your code you didn't use data-target-modal so it will return nAn or unidentified

If this is the button you want to Fetch you might check at this i Already fixed your typo

$html .= '<li><p>' . $r2 . '</p><button data-target-modal="#Modal-Name" data-target-user="'.$r['id'].'id="friendsMessageButton"'. $r['id'] .' class="btn friendsMessageButton">MESSAGE
                </button></li>';

And you should check this querySelectorAll

0

My guess is you need to delegate

You have not posted enough HTML to handle the overlay and I am suspicious of the closest(".messages") in your code

Here is a start

$(function() {
  $("#peopleFriends").on("click", "[data-target-user]", function() {
    $(this).closest("li").find(".messages").toggleClass("active");
  })
})
div.messages {
  display: none;
}

div.active {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" />

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />

<h2 class="peopleHeader divSubContainer" id="peopleFriendsHeader" data-id="peopleFriendsHeader" data-target="peopleFriends" style="cursor:pointer" onclick=hideShowh2(this.getAttribute( "data-id"),this.getAttribute( "data-target"))>Friends
  <button id="refreshButton"><i class="fa fa-refresh" style="font-size:24px"></i></button>
</h2>

<ul class="peopleFriends" id="peopleFriends">
  <li>
    <p>Fred</p><button data-target-user='Joe' id='friendsMessageButtonJoe' class='btn friendsMessageButton'>MESSAGE from Joe</button>
    <div class="messages">
      <p>Message 1</p>
      <p>Message 2</p>
    </div>
  </li>

  <li>
    <p>Fred</p><button data-target-user='Frank' id='friendsMessageButtonFrank' class='btn friendsMessageButton'>MESSAGE from Frank</button>
    <div class="messages">
      <p>Message 1</p>
      <p>Message 2</p>
    </div>
  </li>


</ul>
mplungjan
  • 169,008
  • 28
  • 173
  • 236