1

I am currently working on a multi-user privat chat-system (pretty similar to the Facebook chat). There is a sidebar with all users and when I click on a user a chat window gets dynamically generated by JavaScript. The chat window contains a .chat-container with all messages between the selcted user and the logged in user. The .chat-container has to get updated like every 3 seconds with AJAX, but for some reason I am unable to make it work!

My current try is the following:

Every user-element in the sidebar has a hidden form .chat-ident-form inside it. The form has two inputs "to_user" and "from_user", which values get populated with PHP:

    <div class="sidebar-name">
     <form class="chat-ident-form" action="./src/assets/widgets/chat-widget/get-messages.php" method="post" onclick="submit_ident_form_via_ajax();">
       <a href="javascript:register_popup('<?php echo $member['username'] ?>', '<?php echo $member['username'] ?>');">
          <img class="img-circle chat-sidebar-user-avatar" src="<?php echo $member["avatar"]; ?>" />
          <span><?php echo $member['username'] ?></span>
       </a>
       <input type="hidden" name="to_user" value="<?php echo $member['username'] ?>">
       <input type="hidden" name="from_user" value="<?php echo $_SESSION['username'] ?>">
     </form>
    </div>

When the user clicks on a user-element in the sidebar a chat window opens up (which is working!) and then the trouble begins!

I then want to submit the hidden .chat-ident-form to a PHP-Script (at ./src/assets/widgets/chat-widget/get-messages.php) via AJAX. I currently trigger the AJAX with onclick, when the user clicks on the user-element in the sidebar. The PHP-Script then gathers the massages between the users from the database and echos them as HTML-Code, which I then want to retrieve again via AJAX to display it in the .chat-container.

First things first, the PHP-Script is working. When it gets the neccessary $_POST-Variables it produces the HTML for the messages:

if (isset($_POST["from_user"]) && isset($_POST["to_user"])) {

try {

$from_user = $_POST["chat_user"];
$to_user = $_POST["chat_target_user"];

$query = "SELECT * FROM chat WHERE from_user = :from_user AND to_user = :to_user";

$statement = $db->prepare($query);

$statement->execute(array(':from_user' => $from_user, ':to_user' => $to_user));

$to_messages = $statement->fetchAll(PDO::FETCH_ASSOC);

$from_user = $_POST["chat_target_user"];
$to_user = $_POST["chat_user"];

$query = "SELECT * FROM chat WHERE from_user = :from_user AND to_user = :to_user";

$statement = $db->prepare($query);

$statement->execute(array(':from_user' => $from_user, ':to_user' => $to_user));

$from_messages = $statement->fetchAll(PDO::FETCH_ASSOC);

$all_messages = array_merge($to_messages, $from_messages);

usort($all_messages, "sortFunction");

$html_messages = "";

foreach ($all_messages AS $message) {

    if ($message["from_user"] == $to_user) {

      $html_messages .= "<div class='chat-massage-container'><div class='chat-massage-a'>". $message["message"] ."</div></div>";

    } else {

      $html_messages .= "<div class='chat-massage-container'><div class='chat-massage-b'>". $message["message"] ."</div></div>";

    }

}

echo $html_messages;

} catch (PDOException $ex) {

echo "An error occured!";

}

}

Sadly the PHP-Skript does not receive the neccessary $_POST-Variables. So there has to be something wrong with the AJAX submitting the .chat-ident-form. It looks like this:

function submit_ident_form_via_ajax () {
  $(this).ajaxSubmit(function() {
    getMessages();
   });
setTimeout(submit_ident_form_via_ajax, 3000);
}

function getMessages () {

  var request = new XMLHttpRequest();

  request.onreadystatechange = function () {

    if (request.readyState == 4 && request.status == 200) {

      document.getElementsByClassName('.chat-container').innerHTML = request.responseText;

    }

  };

  request.open('GET', './src/assets/widgets/chat-widget/get-messages.php', true);

  request.send();

  }

Notice that I am using the jQuery Form Plugin for the AJAX. When the submission returns success the getMessages() function is called, which retrieves the HTML from the PHP-Script and displays it in the .chat-container. Well at least in theory it does. In reality, nothing happens. So the form is not submitted by the AJAX and the HTML is neither retrieved from the PHP-Script nor displayed in the .chat-container.

I am pretty new to AJAX and I am completely lost here! What would be the right AJAX to send the .chat-ident-form to the PHP-Script? (Can be with JS, jQuery or jQuery Form Plugin... idc) How should I trigger the submission of the .chat-ident-form? Via onclick - as I currently do - or is there a better way? And then there is also the question: How do I retrieve the HTML echoed by the PHP-Script and display it in the dynamically generated .chat-container? What is the correct AJAX to do that? When does this happen? Does it happen with the submission or does it happen seperatly? How does it get triggered?

So I need to know two things from you guys:

  1. The right AJAX to send the hidden .chat-ident-form and how to trigger it.
  2. The right AJAX to get the HTML echoed in the PHP-Skript and display it in the dynamically generated .chat-container and also when to do this.

Overall I am just confused and my brain hurts after several hours of thinking about it!!! Maybe there is a much easier way, but I dont see it right now. Or maybe my whole thought process is flawed... =/

Anyways, I tried to explain my problems as well as I could. If anything is missing feel free to ask and please have some mercy (this is my first ever question at StackOverflow).

I would be really happy, if anyone has a solution. =)

  • 1
    Your code is vulnerable to [**SQL injection**](https://en.wikipedia.org/wiki/SQL_injection) attacks. You should use prepared statements with bound parameters, via either the [**mysqli**](https://secure.php.net/manual/en/mysqli.prepare.php) or [**PDO**](https://secure.php.net/manual/en/pdo.prepared-statements.php) drivers. [**This post**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) has some good examples. – Alex Howansky Jul 12 '17 at 18:38
  • Attach event handlers in javascript, not in HTML. That allows you to avoid the global namespace and it's much simpler to see what's going on. – Roamer-1888 Jul 12 '17 at 18:47
  • 1
    @AlexHowansky Damn you are right! I coded the PHP-Script rather quickly. I corrected it! Thanks! =) – Ruben Winkler Jul 12 '17 at 18:59
  • @Roamer-1888 Hmmm... okay, I have never done this to be honest. But then I will have a deeper look into that soon! Thanks! :) – Ruben Winkler Jul 12 '17 at 19:00
  • _"I corrected it! Thanks!"_ Wonderful, thank you! Most recipients of that message just don't care. – Alex Howansky Jul 12 '17 at 19:02
  • @AlexHowansky But it is a major security issue! o.O By the way... did I do it correctly? :D – Ruben Winkler Jul 12 '17 at 19:04
  • Don't quote the placeholders in the query strings. Change `WHERE from_user = ':from_user'` to `WHERE from_user = :from_user` etc. – Alex Howansky Jul 12 '17 at 19:05
  • @AlexHowansky True! Again a big thank you! =) – Ruben Winkler Jul 12 '17 at 19:07
  • @RubenWinkler before I post an answer, I need to be clear that this is an end-user page for actually chatting, not a moderator tool for monitoring chats. – Roamer-1888 Jul 13 '17 at 00:01
  • @Roamer-1888 Yes, this is an end-user page. Its going to be for a Social Network. And frankly wtm it is just a privat project of mine. ;) Luckily I fixed my problems. My overall thought process was kinda wrong. Will update the question with my solution soon. ;) – Ruben Winkler Jul 13 '17 at 20:59
  • OK, I have prepared an answer too. It will be interesting to compare yours with mine. – Roamer-1888 Jul 14 '17 at 01:15

0 Answers0