js chat problem

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • js chat problem


    I have a problem with the JS chat. in fact do not work smileys. Please help because I do not know how to do js scripts

  • #2
    JS chat script
    ==========
    var windowFocus = true;
    var username;
    var chatHeartbeatCount = 0;
    var minChatHeartbeat = 1000;
    var maxChatHeartbeat = 33000;
    var chatHeartbeatTime = minChatHeartbeat;
    var originalTitle;
    var blinkOrder = 0;

    var chatboxFocus = new Array();
    var newMessages = new Array();
    var newMessagesWin = new Array();
    var chatBoxes = new Array();
    var smileys = {
    "(angry)":"<img src='../../smileys/(angry).gif'>",
    "(lol)":"<img src='../../smileys/(lol).gif'>",
    "(angry)":"<img src='../../smileys/(angry).gif'>",
    "(love)":"<img src='../../smileys/(love).gif'>",
    "(sorry)":"<img src='chat/smileys/(sorry).gif'>",
    "(why)":"<img src='chat/smileys/(why).gif'>",
    ":D":"<img src='chat/smileys/D).gif'>",
    "":"<img src='chat/smileys/.gif'>",
    "(sorry)":"<img src='chat/smileys/(sorry).gif'>",
    ";)":"<img src='chat/smileys/(happy).gif'>",
    "":"<img src='chat/smileys/(happy).gif'>"
    }
    $(document).ready(function(){
    originalTitle = document.title;
    startChatSession();


    $([window, document]).blur(function(){
    windowFocus = false;
    }).focus(function(){
    windowFocus = true;
    document.title = originalTitle;
    });
    });

    function webcamAccepted(username , stratus) {
    win = window.open('webcam.php?stratus='+stratus+'&hisuse rname='+username ,'webcam','left=20,top=20,width=610,height=500,too lbar=0,resizable=0');
    }
    function webcam(username) {
    win = window.open('webcam.php?hisusername='+username ,'webcam','left=20,top=20,width=610,height=500,too lbar=0,resizable=0');
    }
    function block(username) {
    $.post( "chat1.php?action=block", { username: username }, function(data) {
    alert(data);
    });
    }
    function restructureChatBoxes() {
    align = 0;
    for (x in chatBoxes) {
    chatboxtitle = chatBoxes[x];

    if ($("#chatbox_"+chatboxtitle).css('display') != 'none') {
    if (align == 0) {
    $("#chatbox_"+chatboxtitle).css('right', '20px');
    } else {
    width = (align)*(225+7)+20;
    $("#chatbox_"+chatboxtitle).css('right', width+'px');
    }
    align++;
    }
    }
    }

    function chatWith(chatuser) {
    createChatBox(chatuser);
    $("#chatbox_"+chatuser+" .chatboxtextarea").focus();
    }

    function createChatBox(chatboxtitle,minimizeChatBox) {
    if ($("#chatbox_"+chatboxtitle).length > 0) {
    if ($("#chatbox_"+chatboxtitle).css('display') == 'none') {
    $("#chatbox_"+chatboxtitle).css('display','block ') ;
    restructureChatBoxes();
    }
    $("#chatbox_"+chatboxtitle+" .chatboxtextarea").focus();
    return;
    }

    $(" <div />" ).attr("id","chatbox_"+chatboxtitle)
    .addClass("chatbox")
    .html('<div class="chatboxhead"><div class="chatboxtitle">'+chatboxtitle+' <a href="javascript:void(0)" onclick="javascript:webcam(\''+chatboxtitle+'\');" ><img src="../../images/webcam.png" alt="camera"> </a></div><div class="chatboxoptions"><a href="javascript:void(0)" onclick="javascript:toggleChatBoxGrowth(\''+chatbo xtitle+'\')">-</a> <a href="javascript:void(0)" onclick="javascript:closeChatBox(\''+chatboxtitle+ '\')">X</a></div>'+
    '<br clear="all"/> '+

    '</div><div class="chatboxcontent"></div><div class="chatboxinput"><textarea class="chatboxtextarea" onkeydown="javascript:return checkChatBoxInputKey(event,this,\''+chatboxtitle+' \');"></textarea></div>')
    .appendTo($( "body" ));

    $("#chatbox_"+chatboxtitle).css('bottom', '0px');

    chatBoxeslength = 0;

    for (x in chatBoxes) {
    if ($("#chatbox_"+chatBoxes[x]).css('display') != 'none') {
    chatBoxeslength++;
    }
    }

    if (chatBoxeslength == 0) {
    $("#chatbox_"+chatboxtitle).css('right', '20px');
    } else {
    width = (chatBoxeslength)*(225+7)+20;
    $("#chatbox_"+chatboxtitle).css('right', width+'px');
    }

    chatBoxes.push(chatboxtitle);

    if (minimizeChatBox == 1) {
    minimizedChatBoxes = new Array();

    if ($.cookie('chatbox_minimized')) {
    minimizedChatBoxes = $.cookie('chatbox_minimized').split(/\|/);
    }
    minimize = 0;
    for (j=0;j<minimizedChatBoxes.length;j++) {
    if (minimizedChatBoxes[j] == chatboxtitle) {
    minimize = 1;
    }
    }

    if (minimize == 1) {
    $('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display','none');
    $('#chatbox_'+chatboxtitle+' .chatboxinput').css('display','none');
    }
    }

    chatboxFocus[chatboxtitle] = false;

    $("#chatbox_"+chatboxtitle+" .chatboxtextarea").blur(function(){
    chatboxFocus[chatboxtitle] = false;
    $("#chatbox_"+chatboxtitle+" .chatboxtextarea").removeClass('chatboxtextareasel ected');
    }).focus(function(){
    chatboxFocus[chatboxtitle] = true;
    newMessages[chatboxtitle] = false;
    $('#chatbox_'+chatboxtitle+' .chatboxhead').removeClass('chatboxblink');
    $("#chatbox_"+chatboxtitle+" .chatboxtextarea").addClass('chatboxtextareaselect ed');
    });

    $("#chatbox_"+chatboxtitle).click(function() {
    if ($('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display') != 'none') {
    $("#chatbox_"+chatboxtitle+" .chatboxtextarea").focus();
    }
    });

    $("#chatbox_"+chatboxtitle).show();
    }


    function chatHeartbeat(){
    var itemsfound = 0;

    if (windowFocus == false) {

    var blinkNumber = 0;
    var titleChanged = 0;
    for (x in newMessagesWin) {
    if (newMessagesWin[x] == true) {
    ++blinkNumber;
    if (blinkNumber >= blinkOrder) {
    document.title = x+' says...';
    titleChanged = 1;
    break;
    }
    }
    }

    if (titleChanged == 0) {
    document.title = originalTitle;
    blinkOrder = 0;
    } else {
    ++blinkOrder;
    }

    } else {
    for (x in newMessagesWin) {
    newMessagesWin[x] = false;
    }
    }

    for (x in newMessages) {
    if (newMessages[x] == true) {
    if (chatboxFocus[x] == false) {
    //FIXME: add toggle all or none policy, otherwise it looks funny
    $('#chatbox_'+x+' .chatboxhead').toggleClass('chatboxblink');
    }
    }
    }

    $.ajax({
    url: "chat1.php?action=chatheartbeat",
    cache: false,
    dataType: "json",
    success: function(data) {


    $.each(data.items, function(i,item){
    if (item) { // fix strange ie bug
    //alert(item.m);
    chatboxtitle = item.f;

    if ($("#chatbox_"+chatboxtitle).length <= 0) {
    createChatBox(chatboxtitle);
    }
    if ($("#chatbox_"+chatboxtitle).css('display') == 'none') {
    $("#chatbox_"+chatboxtitle).css('display','block ') ;
    restructureChatBoxes();
    }

    if (item.s == 1) {
    item.f = username;
    }

    if (item.s == 2) {
    $("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxinfo">'+item.m+'</span></div>');
    } else {
    newMessages[chatboxtitle] = true;
    newMessagesWin[chatboxtitle] = true;
    $("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+item.f+':&nbsp;&nbsp; </span><span class="chatboxmessagecontent">'+item.m+'</span></div>');
    }

    $("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop($("#chatbox_"+chatboxt itle+" .chatboxcontent")[0].scrollHeight);
    itemsfound += 1;
    }
    });

    chatHeartbeatCount++;

    if (itemsfound > 0) {
    chatHeartbeatTime = minChatHeartbeat;
    chatHeartbeatCount = 1;
    } else if (chatHeartbeatCount >= 10) {
    chatHeartbeatTime *= 2;
    chatHeartbeatCount = 1;
    if (chatHeartbeatTime > maxChatHeartbeat) {
    chatHeartbeatTime = maxChatHeartbeat;
    }
    }

    setTimeout('chatHeartbeat();',chatHeartbeatTime);
    }});
    }

    function closeChatBox(chatboxtitle) {
    $('#chatbox_'+chatboxtitle).css('display','none');
    restructureChatBoxes();

    $.post("chat1.php?action=closechat", { chatbox: chatboxtitle} , function(data){
    });

    }

    function toggleChatBoxGrowth(chatboxtitle) {
    if ($('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display') == 'none') {

    var minimizedChatBoxes = new Array();

    if ($.cookie('chatbox_minimized')) {
    minimizedChatBoxes = $.cookie('chatbox_minimized').split(/\|/);
    }

    var newCookie = '';

    for (i=0;i<minimizedChatBoxes.length;i++) {
    if (minimizedChatBoxes[i] != chatboxtitle) {
    newCookie += chatboxtitle+'|';
    }
    }

    newCookie = newCookie.slice(0, -1)


    $.cookie('chatbox_minimized', newCookie);
    $('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display','block');
    $('#chatbox_'+chatboxtitle+' .chatboxinput').css('display','block');
    $("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop($("#chatbox_"+chatboxt itle+" .chatboxcontent")[0].scrollHeight);
    } else {

    var newCookie = chatboxtitle;

    if ($.cookie('chatbox_minimized')) {
    newCookie += '|'+$.cookie('chatbox_minimized');
    }


    $.cookie('chatbox_minimized',newCookie);
    $('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display','none');
    $('#chatbox_'+chatboxtitle+' .chatboxinput').css('display','none');
    }

    }
    function sendChat(chatboxtextarea , chatboxtitle, action) {
    message = $(chatboxtextarea).val();
    message = message.replace(/^\s+|\s+$/g,"");

    $(chatboxtextarea).val('');
    $(chatboxtextarea).focus();
    $(chatboxtextarea).css('height','44px');
    if (message != '') {
    $.post("chat1.php?action=sendchat", {to: chatboxtitle, message: message , action:action} , function(data){
    message = message.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");
    $("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+username+':&nbsp;&nbs p;</span><span class="chatboxmessagecontent">'+message+'</span></div>');
    $("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop($("#chatbox_"+chatboxt itle+" .chatboxcontent")[0].scrollHeight);
    });
    }
    chatHeartbeatTime = minChatHeartbeat;
    chatHeartbeatCount = 1;
    }


    function checkChatBoxInputKey(event,chatboxtextarea,chatbox title) {

    if(event.keyCode == 13 && event.shiftKey == 0) {
    sendChat(chatboxtextarea , chatboxtitle, 0);

    return false;
    }

    var adjustedHeight = chatboxtextarea.clientHeight;
    var maxHeight = 94;

    if (maxHeight > adjustedHeight) {
    adjustedHeight = Math.max(chatboxtextarea.scrollHeight, adjustedHeight);
    if (maxHeight)
    adjustedHeight = Math.min(maxHeight, adjustedHeight);
    if (adjustedHeight > chatboxtextarea.clientHeight)
    $(chatboxtextarea).css('height',adjustedHeight+8 +'px');
    } else {
    $(chatboxtextarea).css('overflow','auto');
    }

    }

    function startChatSession(){
    $.ajax({
    url: "chat1.php?action=startchatsession",
    cache: false,
    dataType: "json",
    success: function(data) {

    username = data.username;

    $.each(data.items, function(i,item){
    if (item) { // fix strange ie bug

    chatboxtitle = item.f;

    if ($("#chatbox_"+chatboxtitle).length <= 0) {
    createChatBox(chatboxtitle,1);
    }

    if (item.s == 1) {
    item.f = username;
    }

    if (item.s == 2) {
    $("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxinfo">'+item.m+'</span></div>');
    } else {
    $("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+item.f+':&nbsp;&nbsp; </span><span class="chatboxmessagecontent">'+item.m+'</span></div>');
    }
    }
    });

    for (i=0;i<chatBoxes.length;i++) {
    chatboxtitle = chatBoxes[i];
    $("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop($("#chatbox_"+chatboxt itle+" .chatboxcontent")[0].scrollHeight);
    setTimeout('$("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop($("#chatbox_"+chatboxt itle+" .chatboxcontent")[0].scrollHeight);', 100); // yet another strange ie bug
    }

    setTimeout('chatHeartbeat();',chatHeartbeatTime);

    }});
    }



    jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
    options = options || {};
    if (value === null) {
    value = '';
    options.expires = -1;
    }
    var expires = '';
    if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
    var date;
    if (typeof options.expires == 'number') {
    date = new Date();
    date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
    } else {
    date = options.expires;
    }
    expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
    }
    // CAUTION: Needed to parenthesize options.path and options.domain
    // in the following expressions, otherwise they evaluate to undefined
    // in the packed version for some reason...

    var path = options.path ? '; path=' + (options.path) : '';
    var domain = options.domain ? '; domain=' + (options.domain) : '';
    var secure = options.secure ? '; secure' : '';
    document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
    var cookies = document.cookie.split(';');
    for (var i = 0; i < cookies.length; i++) {
    var cookie = jQuery.trim(cookies[i]);
    // Does this cookie string begin with the name we want?
    if (cookie.substring(0, name.length + 1) == (name + '=')) {
    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
    break;
    }
    }
    }
    return cookieValue;
    }
    };
    Last edited by srecnica; 27.11.16, 15:31.

    Comment


    • #3
      chat.php file
      =========
      <?php
      include("sql.php");
      session_start();


      if ($_GET['action'] == "chatheartbeat") { chatHeartbeat(); }
      if ($_GET['action'] == "sendchat") { sendChat(); }
      if ($_GET['action'] == "closechat") { closeChat(); }
      if ($_GET['action'] == "startchatsession") { startChatSession(); }
      if ($_GET['action'] == "block") { block(); }
      if ($_GET['action'] == "webcam") { webcam(); }

      if (!isset($_SESSION['chatHistory'])) {
      $_SESSION['chatHistory'] = array();
      }

      if (!isset($_SESSION['openChatBoxes'])) {
      $_SESSION['openChatBoxes'] = array();
      }

      function webcam() {
      $username = $_POST["username"];
      echo "$username ke prihvatio poziv";
      exit(0);
      }
      function block() {
      $username = $_POST["username"];
      echo "$username je blokiran";
      exit(0);
      }

      function chatHeartbeat() {
      $sql="replace into peer_userstatus set date=now(), username='".$_SESSION['username']."',uid='".$_SESSION['uid']."'";
      mysql_query($sql);
      $sql = "select * from peer_chat where (peer_chat.to = '".mysql_real_escape_string($_SESSION['username'])."' AND recd = 0) order by id ASC";
      $query = mysql_query($sql);
      $items = '';

      $chatBoxes = array();

      while ($chat = mysql_fetch_array($query)) {

      if (!isset($_SESSION['openChatBoxes'][$chat['from']]) && isset($_SESSION['chatHistory'][$chat['from']])) {
      $items = $_SESSION['chatHistory'][$chat['from']];
      }
      if ($chat['action']==0) $chat['message'] = sanitize($chat['message']);
      if ($chat['action']==1) {
      $from = $chat['from'];
      $stratus = $chat['stratus'];
      $chat['message'] = '<a href=# onclick=webcamAccepted(\''.$from.'\',\''.$stratus. '\')>Klinki da prihvatis video chat sa </a>'.$chat['from'].' .';

      }
      $items .= <<<EOD
      {
      "s": "0",
      "f": "{$chat['from']}",
      "m": "{$chat['message']}"
      },
      EOD;

      if (!isset($_SESSION['chatHistory'][$chat['from']])) {
      $_SESSION['chatHistory'][$chat['from']] = '';
      }

      $_SESSION['chatHistory'][$chat['from']] .= <<<EOD
      {
      "s": "0",
      "f": "{$chat['from']}",
      "m": "{$chat['message']}"
      },
      EOD;

      unset($_SESSION['tsChatBoxes'][$chat['from']]);
      $_SESSION['openChatBoxes'][$chat['from']] = $chat['sent'];
      }

      if (!empty($_SESSION['openChatBoxes'])) {
      foreach ($_SESSION['openChatBoxes'] as $chatbox => $time) {
      if (!isset($_SESSION['tsChatBoxes'][$chatbox])) {
      $now = time()-strtotime($time);
      $time = date('g:iA M dS', strtotime($time));
      $dtot = date("d-m-y - H:i:s",strtotime($time));
      $message = "Napisano $dtot ";
      if ($now > 180) {
      $items .= <<<EOD
      {
      "s": "2",
      "f": "$chatbox",
      "m": "{$message}"
      },
      EOD;

      if (!isset($_SESSION['chatHistory'][$chatbox])) {
      $_SESSION['chatHistory'][$chatbox] = '';
      }

      $_SESSION['chatHistory'][$chatbox] .= <<<EOD
      {
      "s": "2",
      "f": "$chatbox",
      "m": "{$message}"
      },
      EOD;
      $_SESSION['tsChatBoxes'][$chatbox] = 1;
      }
      }
      }
      }

      $sql = "update peer_chat set recd = 1 where peer_chat.to = '".mysql_real_escape_string($_SESSION['username'])."' and recd = 0";
      $query = mysql_query($sql);

      if ($items != '') {
      $items = substr($items, 0, -1);
      }
      header('Content-type: application/json');
      ?>
      {
      "items": [
      <?php echo $items;?>
      ]
      }

      <?php
      exit(0);
      }

      function chatBoxSession($chatbox) {

      $items = '';

      if (isset($_SESSION['chatHistory'][$chatbox])) {
      $items = $_SESSION['chatHistory'][$chatbox];
      }

      return $items;
      }

      function startChatSession() {
      $items = '';
      if (!empty($_SESSION['openChatBoxes'])) {
      foreach ($_SESSION['openChatBoxes'] as $chatbox => $void) {
      $items .= chatBoxSession($chatbox);
      }
      }


      if ($items != '') {
      $items = substr($items, 0, -1);
      }

      header('Content-type: application/json');
      ?>
      {
      "username": "<?php echo $_SESSION['username'];?>",
      "items": [
      <?php echo $items;?>
      ]
      }

      <?php


      exit(0);
      }

      function sendChat() {
      $from = $_SESSION['username'];
      $to = $_POST['to'];
      $message = $_POST['message'];
      $action = $_POST['action'];

      $_SESSION['openChatBoxes'][$_POST['to']] = date('Y-m-d H:i:s', time());
      $messagesan = $message;
      if ($action == 0) $messagesan = sanitize($message);

      if (!isset($_SESSION['chatHistory'][$_POST['to']])) {
      $_SESSION['chatHistory'][$_POST['to']] = '';
      }

      $_SESSION['chatHistory'][$_POST['to']] .= <<<EOD
      {
      "s": "1",
      "f": "{$to}",
      "m": "{$messagesan}"
      },
      EOD;


      unset($_SESSION['tsChatBoxes'][$_POST['to']]);



      $sql = "insert into peer_chat (peer_chat.from , peer_chat.to , message,sent,action) values ('".mysql_real_escape_string($from)."', '".mysql_real_escape_string($to)."','".mysql_real_ escape_string($message)."',NOW(),$action)";

      $query = mysql_query($sql);
      echo "1";
      exit(0);
      }

      function closeChat() {

      unset($_SESSION['openChatBoxes'][$_POST['chatbox']]);

      echo "1";
      exit(0);
      }

      function sanitize($text) {
      $text = htmlspecialchars($text, ENT_QUOTES);
      $text = str_replace("\n\r","\n",$text);
      $text = str_replace("\r\n","\n",$text);
      $text = str_replace("\n","<br>",$text);
      return $text;
      }

      Comment


      • #4
        please help
        do not show smilies

        Comment


        • #5
          open your js chat in your google chrome and use chrome dev tools, navigate to console and view the errors, screenshot or tell us what the error message says.

          PS: Use F12 to toggle chrome dev tools

          Comment


          • #6
            ailed to load resource: the server http://happy.srecnica.com/web/script.js
            Failed to load resource: the serverresponded with a status of 404 (Not Found)

            Comment


            • #7
              script.js is missing, thats why. I can easily fix it and write a better script for you, but I dont offer free services..

              Comment


              • srecnica
                srecnica commented
                Editing a comment
                thanks for your reply

            • #8
              solved
              this function
              ====================
              function sanitize($text) {
              $text = htmlspecialchars($text, ENT_QUOTES);
              $text = str_replace("\n\r","\n",$text);
              $text = str_replace("\r\n","\n",$text);
              $text = str_replace("\n","<br>",$text);
              return $text;
              }
              ====================
              replace this
              function sanitize($text) {
              $text = htmlspecialchars($text, ENT_QUOTES);
              $text = str_replace("\n\r","\n",$text);
              $text = str_replace("\r\n","\n",$text);
              $text = str_replace("\n","<br>",$text);
              $sql = "SELECT * FROM ibvf_smilies";
              $smilies = mysql_query($sql);
              while($smilie=mysql_fetch_array($smilies))
              {
              $scode = $smilie[1];
              $spath = $smilie[2];
              $text = str_replace("$scode","<img src='$spath\' alt=\'$scode\'/>",$text);
              }
              return $text;
              }
              =====================
              Last edited by srecnica; 08.12.16, 22:16.

              Comment

              Working...
              X