-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.

  • 1
    **Warning:** You are wide open to [SQL Injections](https://stackoverflow.com/a/60496/1839439) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Sep 10 '20 at 11:42
  • Does this answer your question? [Get variable from PHP file using JQuery/AJAX](https://stackoverflow.com/questions/10341434/get-variable-from-php-file-using-jquery-ajax) – Atilla Arda Açıkgöz Sep 10 '20 at 11:45

1 Answers1

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.

ADyson
  • 57,178
  • 14
  • 51
  • 63
  • This code is not working. Any other alternative is possible? – Aryayan Roy Sep 11 '20 at 04:26
  • 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. – ADyson Sep 11 '20 at 08:07
  • There is no response. – Aryayan Roy Sep 14 '20 at 04:55
  • 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? – ADyson Sep 14 '20 at 08:07
  • 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. – ADyson Sep 14 '20 at 08:27