Zeu Zeu - 3 months ago 17
jQuery Question

jquery chat Trying to get user id from a user that i want to send a message

i have a chat script similar like fb but i have a question, i want to extract user id from an open chat window (like fb) and i don;t know how to do that and to configurate the submit php file to take that id from the user that i want to send the message and insert it to my table. Ex: from id: 1 (me) message toUser id: 2 <-(this toUser id that i want to grab from id 2 window)

I don't have a clue how to do that. Any help appreciated!

This is my db structure:

| id | from | toUser | message |
23 1 (me) 2 <-(this is the user that i want to get)


This is the index html:

<a href='#' id='$id'><-(this Id that i want grab)</span> <em>$name $surename</em></a> <-- This is the link from all users name with id's

<script type="text/javascript">

$(document).ready(function() {

$("#message").keyup(function(evt) {
if(evt.which == 13) {
var toUser = $('#toUser').val();
$.post("submit.php", {
message: $("#message").val(),
toUser: $("#toUser").val(),},

function(data){

$("#message").val("");});
}
});
});
</script>
<div class='chat-textarea'>
<textarea id="message" class="form-control autogrow" placeholder="Type your message"> </textarea>
</div>


The submit php file:

<?php
if(isset($_POST['message'])){

$dbhost = 'localhost';
$dbuser = 'user';
$dbpass = 'pass';

$conn = mysql_connect($dbhost, $dbuser, $dbpass)
or die ('Error connecting to mysql');

$dbname = 'chat';

mysql_select_db($dbname);

$from = $_SESSION['user']; <- This is me

$message = isset($_POST['message']) ? $_POST['message'] : '';

$toUser = $_POST['toUser']; <- this is not working,return value 0

if($message != ''){
$sql = "INSERT INTO `messages` VALUES ('','$message','$from','$toUser'";
mysql_query($sql);
}
}
?>

Answer
// your loop for users 
<a href='#' id='toUser' data-message-id="1">
 <a href='#' class='toUser' data-message-id="2">
// loop completes here
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script type="text/javascript">  

    $(document).ready(function() {

         $("#message").keyup(function(evt) {   
         if(evt.which == 13) {
           var toUser = $('.toUser').attr('data-message-id');
           alert(toUser);
           $.post("submit.php", { 
            message: $("#message").val(),
            toUser: toUser,},

        function(data){ 

        $("#message").val("");});
    }
     });
    });
</script>
<div class='chat-textarea'>
    <textarea id="message" class="form-control autogrow" placeholder="Type your message"> </textarea>  
</div>