0

I using the below php chat script to create chat section between two users on my web app. I am having a problem with the Ajax posting. When a user submits a chat it doesn't post or show in the chat window. I tried to inspect the error and this is the error message

Failed to load resource: the server responded with a status of 404 (Not Found)

The same error message is shown for submit.php and refresh.php.

Here's my code:

JS

//CHAT FUNCTION

var lastTimeID = 0;

$(document).ready(function() {
  $('#btnSend').click( function() {
    sendChatText();
    $('#chatInput').val("");
  });
  startChat();
});

function startChat(){
  setInterval( function() { getChatText(); }, 2000);
}

function getChatText() {
  $.ajax({
    type: "GET",
    url: "refresh.php?lastTimeID=" + lastTimeID
  }).done( function( data )
  {
    var jsonData = JSON.parse(data);
    var jsonLength = jsonData.results.length;
    var html = "";
    for (var i = 0; i < jsonLength; i++) {
      var result = jsonData.results[i];
      html += '<div style="color:#' + result.color + '">(' + result.chattime + ') <b>' + result.usrname +'</b>: ' + result.chattext + '</div>';
      lastTimeID = result.id;
    }
    $('#view_ajax').append(html);
  });
}

function sendChatText(){
  var chatInput = $('#chatInput').val();
  if(chatInput != ""){
    $.ajax({
      type: "GET",
      url: "submit.php?chattext=" + encodeURIComponent( chatInput )
    });
  }
}

chatClass.php

<?PHP
 class chatClass
  {
    public static function getRestChatLines($id)
    {
      $arr = array();
      $jsonData = '{"results":[';
      $statement = $db->prepare( "SELECT id, usrname, color, chattext, chattime FROM chat WHERE id > ? and chattime >= DATE_SUB(NOW(), INTERVAL 1 HOUR)");
      $statement->bind_param( 'i', $id);
      $statement->execute();
      $statement->bind_result( $id, $usrname, $color, $chattext, $chattime);
      $line = new stdClass;
      while ($statement->fetch()) {
        $line->id = $id;
        $line->usrname = $usrname;
        $line->color = $color;
        $line->chattext = $chattext;
        $line->chattime = date('H:i:s', strtotime($chattime));
        $arr[] = json_encode($line);
      }
      $statement->close();
      $jsonData .= implode(",", $arr);
      $jsonData .= ']}';
      return $jsonData;
    }

    public static function setChatLines( $chattext, $usrname, $color) {
      $statement = $db->prepare( "INSERT INTO chat( usrname, color, chattext) VALUES(?, ?, ?)");
      $statement->bind_param( 'sss', $usrname, $color, $chattext);
      $statement->execute();
      $statement->close();
    }
  }
  ?>

submit.php

<?php
  require_once( "chatClass.php" );
  $chattext = htmlspecialchars( $_GET['chattext'] );
  chatClass::setChatLines( $chattext, $_SESSION['usrname'], $_SESSION['color']);
?>

refresh.php

<?php
  require_once( "chatClass.php" );
  $id = intval( $_GET[ 'lastTimeID' ] );
  $jsonData = chatClass::getRestChatLines( $id );
  print $jsonData;
?>
Dharman
  • 30,962
  • 25
  • 85
  • 135
  • 404 Not Found has quite a simple cause usually - your URL is incorrect. Use the Network Tool in the Developer Tools to see what the full URL being called by your AJAX is, and check whether that matches the one you want. Perhaps those files are in a different folder to the one where your HTML/JS code is loaded from, for example? – ADyson Jan 23 '20 at 20:29
  • BTW it would almost certainly be a lot more efficient to write a chat app using websockets, anyway, rather than AJAX. – ADyson Jan 23 '20 at 20:30
  • Thanks Adyson. I was able to fix the 404 Not found issue following your direction. However, I'm still try to trace why my chat isn't insetting into db. Regarding websockets, I tried using it before but I have issues with connections. – Louis Web Solutions Jan 23 '20 at 21:22
  • I can't help you with the inserting without some more debugging info. Have you got full error logging enabled? See https://stackify.com/php-error-logs-guide/ (php error logging/reporting) and https://stackoverflow.com/a/14578644/5947043 (mysqli exception handling) and ensure everything is enabled. Then run the code again and see if any problems are highlighted in the log file. (And if it was me, I would send the chat text in the request body of a POST request, not GET on the querystring - you can encounter issues with the length of URL, plus it's not very private, since URLs get logged.) – ADyson Jan 23 '20 at 21:26
  • Another issue I can potentially see is with your session data - you don't seem to be calling `session_start();` in either submit.php or refresh.php. It is very well documented that you have to do that in every script where you want to use the session (apart from scripts which are included into other scripts via include/require commands). I would guess maybe you are getting errors/warnings about that. – ADyson Jan 23 '20 at 21:27
  • re websockets, I'm sure it's possible to get it to work, thousands of sites use them successfully. But of course we can't help with that unless you post a separate question detailing the specific issues you've found. – ADyson Jan 23 '20 at 21:28
  • I have an include file with session_start() at the top of the file. I'll try websockets again and post my question where necessary. Thanks for your assistance. – Louis Web Solutions Jan 23 '20 at 21:57

0 Answers0