-2

I have created a chat website. I send the message with AJAX to PHP and the MySql Database. The messages are fetched using AJAX which runs per second. But this lead to fetch of all the messages (from starting to end). I came with an solution that I will pass the last message ID to the AJAX/JAVA SCRIPT and then fetch only the messages which are more than that.

Here is the Java Script / AJAX

function fetchdata(){
var cuser = //id of the current user 
var ouser = //id of the other user
 $.ajax({
  url: "messagesprocess.php",
  type: "POST",
  data : {cuser:cuser, ouser:ouser},
  success: function(read){
    $("#readarea").html(read);
  }
 });
}

Here is the PHP code to get messages:

$sql = "SELECT id, fromid,message,toid FROM messages WHERE (fromid={$_POST['cuser']} AND toid={$_POST['ouser']}) OR (fromid={$_POST['ouser']} AND toid={$_POST['cuser']})";
$result = mysqli_query($conn, $sql) or ("Query Failed");

while($row=mysqli_fetch_assoc($result)){
  if($row["fromid"]==$_POST['cuser']){
    echo "<div class='cuser'>".$row["message"]."</div>";
  }else{
    echo "<div class='ouser'>".$row["message"]."</div>";
  }
}

Here I want to get the ID (message) in the Java Script function back from the PHP and use it as a variable for fetching the messages which will be more than it.

2

1 Answer 1

0

You should return JSON from the PHP, instead of HTML. That way you can return an object with properties such as ID, message, etc. Then you can use Javascript to store the latest ID, and also to put the message into your page with the relevant HTML.

Something like this:

PHP:

$sql = "SELECT id, fromid,message,toid FROM messages WHERE (fromid={$_POST['cuser']} AND toid={$_POST['ouser']}) OR (fromid={$_POST['ouser']} AND toid={$_POST['cuser']})";
if (!empty($_POST["lastid"]) $sql .= " AND id > {$_POST['lastid']}";

$result = mysqli_query($conn, $sql) or ("Query Failed");
$messages = array();

while($row=mysqli_fetch_assoc($result)){
  $messages[] = $row;
}

echo json_encode($messages);

JS:

//make this global so it persists beyond each call to fetchdata
var lastMessageID = null;

function fetchdata()
{
  var cuser = //id of the current user 
  var ouser = //id of the other user
  $.ajax({
    url: "messagesprocess.php",
    type: "POST",
    dataType: "json",
    data : { cuser: cuser, ouser: ouser, lastid: lastMessageID },
    success: function(read) {
      for (var i = 0; i < read.length; i++)
      {
        var className = "ouser";
        if (read[i].fromid == cuser) classname = "cuser";

        $("#readarea").append("<div class='" + className + "'>" + read[i].message + "</div>");
        lastMessageID = read[i].id;
      }
    }
 });
}

P.S. Please also take note of the comment about about SQL injection and fix your query code, urgently. I haven't done it here for the sake of brevity, but it must not be ignored.

Sign up to request clarification or add additional context in comments.

5 Comments

This code is not working. Any other alternative is possible?
Can you be more specific please? "Not working" could mean anything. Maybe there is just a small problem we can fix. So, what exactly happens when you run this code - is there a specific error in PHP or Javascript, and have you checked in the right places for those? or does it not behave exactly as you wanted? If you give some details, I can help you.
There is no response.
That's unlikely. There must be some response from the server, even if it's an error. Did you check the Network tool in your browser and watch for calls to messagesprocess.php appearing?
Also have you checked the Console for any error messages of any sort? And have you checked your PHP error log? If you appear to get no response, that's when you start searching for errors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.