0

I am creating a chat application and I have a menu at the left that contains the people which I want to chat with. I used JQuery and ajax it's working properly it's getting the messages but it wont load unless or until I click at the contact, it will load. I want it to load every 10 seconds.

This is my JQuery code:

    $('.contact').click(function(){
    $('.box').show();
    var username = $(this).find('.username').attr('id');
    var id = $(this).closest('.contact').attr('id');
    $('.name').html(fnalnc);
    $.ajax({
            url: 'ajax/chat.php',
            type: 'POST',
            data: {'id':id},
            async: false,
            cashe: false,
            success: function(data){
                $('#chat').html(data);
            }
        });
    });

And the $(.box).show(); it will just show 1 box that comes to the bottom and I want it to show more than 1 box by clicking at the contact just like Facebook.

HTML:

<div class='contact' id='<?php echo "$user_id";?>'></div>
<span class='username' id='<?php echo "$username";?>'><?php echo "$username";?></span>
<div id='chat'></div>
Gin
  • 3
  • 2
  • What are you doing to try and make it "load" every 10 seconds? You could look into something like `setInterval()`. Look up terms like "long polling" for continually requesting data from the server. Also take a look at "web sockets" for ways in which the server can push data to the browser. – David Jul 17 '14 at 17:07
  • If your looking to build a javascript chat application, I would suggest looking into node.js instead. http://tutorialzine.com/2014/03/nodejs-private-webchat/ – Mark Jul 17 '14 at 17:08
  • This question here may answer yours: http://stackoverflow.com/questions/4542863/jquery-ajax-call-with-timer – xDaevax Jul 17 '14 at 17:08
  • I used it I put that ajax code inside a function and I used setInterval then the browser will get stuck – Gin Jul 17 '14 at 17:08
  • This behaviour is due to ajax call inside `click` event. As suggested, use `setInterval(function(){ajax}, 10000); // 10000ms = 10s`. – Marko Gresak Jul 17 '14 at 17:09
  • @maremp inside the click event? I want it to load without the click event – Gin Jul 17 '14 at 17:11
  • I've said your error is due to using ajax call inside click event handler, which means that your ajax call will only occur when user clicks on `.contact`, your current code has no functionality to trigger on time interval. Look at @xDaevax answer for correct solution. – Marko Gresak Jul 17 '14 at 17:45

2 Answers2

1

You need to split out the code that does the Ajax call into it's own function. Then, you can call it both from a click and a setInterval like below.

Edit: This is a snippet taken from my fiddle.

Essentially, it wires up each box as it's own chat container, and has an interval timer on each that only updates when the box is visible.

$(document).ready(function () {
    var box = $('.box')[0]; //single copy of the target box
    $('.contact').click(function () {
        var id = $(this).closest('.contact').attr('id'); // load the user id
        if ($(".chat-windows").find("#" + id + "-window").exists()) {
            if($(".chat-windows").find("#" + id + "-window").is(":visible")) {
            //Do nothing, because the window is already there
            } else {
                $(".chat-windows").find("#" + id + "-window").fadeIn(200).css("display", "inline-block");
            }
        } else {
            //This is a new box, so show it
            var newBox = box.cloneNode();
            var windows = $(".chat-windows");
            $(newBox).find(".chat-header").text(id);
            $(newBox).prop("id", id + "-window");
            //var username = $(this).find('.username').attr('id');                   
            windows.append($(newBox));
            $(newBox).fadeIn(200).css("display", "inline-block");
            updateChat({
                ContactID: id
            });
            setInterval(function() {

                if($(newBox).is(":visible")) {
                    updateChat({ContactID: id});
                } else {
                    //do nothing so we aren't updating things that aren't seen and wasting time
                } // end if/else
            }, 10000); // fire every 10 seconds for this box
        } // end if/else

    });
    $(document).on("click", ".close-chat", function(e) {
        $(e.currentTarget).parent().fadeOut(100)[0].removeNode(); 
    });
});

//Global prototype function to determine if selectors return null
$.fn.exists = function () {
    return this.length !== 0;
}; // end function exists

function updateChat(args) {
    //Do your Ajax here
    /*$.ajax({
            url: 'ajax/chat.php',
            type: 'POST',
            data: {
                'id': args.ContactID
            },
            async: false,
            cashe: false,
            success: function (data) {
                $('#chat').html(data);
            }
        });*/
    $("#" + args.ContactID + "-window").find(".messages").append("<li>" + "My Message" + "</li>");
}

I have created a fiddle that demonstrates this here: http://jsfiddle.net/xDaevax/7efVX/

I'm not clear on exactly which parts of your code should go in the ChatFunction, but you should be able to get the general idea from this code and my example regardless of what you are trying to accomplish with the chat.

xDaevax
  • 2,012
  • 2
  • 25
  • 36
  • I used your code but it made my browser very slow. And the message got hidden – Gin Jul 17 '14 at 18:01
  • Well, my code as it is in my answer is just an illustration. I can make it more helpful if you add your HTML markup and the rest of the javascript in your question. – xDaevax Jul 17 '14 at 18:11
  • When you say load in your question, do you mean you want the page to check the server for updates every 10 seconds and update the contents of each box, or do you mean something else? – xDaevax Jul 17 '14 at 18:29
  • I mean now while I am chatting for example with my friend when I click send it should appear dynamically to the chatbox without clicking at the contact or refreshing the browser and it should appear for him also not only appending – Gin Jul 17 '14 at 18:32
  • Okay, the scope of your question just became apparent to me. I will update my answer, but there are many other things to consider (what if you have 15 chats open for example, then 16 users will have a window that is calling the server every 10 seconds and one user that is calling the server 16 times every 10 seconds). This may not scale well and you'll want to perhaps make one ajax post to return all messages for a user, but that is way outside the scope of this question. – xDaevax Jul 17 '14 at 18:44
  • @Gin Updated my fiddle in my answer – xDaevax Jul 17 '14 at 19:00
  • do you know why when I setInterval will make my browser very slow and then crash I want it to load automatically without clicking at the contact when the box is already visible Please help me in this – Gin Jul 17 '14 at 19:19
  • Gin, I would love to chat, but you don't have enough reputation yet. It runs fine on my pc, you should ask another question related to the slowness as it is outside the scope of this question. – xDaevax Jul 17 '14 at 19:26
  • Could I ask you in Facebook if you can. If you can't then it's okay – Gin Jul 17 '14 at 19:31
  • We may be able to try later, I can't do that now. Why don't you try gaining some rep by contributing to the community, then we may be able to chat here later. – xDaevax Jul 17 '14 at 19:33
  • I can chat with you in my brother's account in stackoverflow he has reputation to chat – Gin Jul 17 '14 at 19:34
0

you must use set inter val in js work with milisec:

setInterval(function(){$('.box').show();}, 10000);

$('.box').show(); run every 10 sec 10000mil = 10 sec

or if need some other code you can replace with $('.box').show(); in this code.

and setInterval info is here

A1Gard
  • 4,070
  • 4
  • 31
  • 55