Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8986991
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T21:41:02+00:00 2026-06-15T21:41:02+00:00

I’m trying to create a Javascript chat, with Python on the backend. This is

  • 0

I’m trying to create a Javascript chat, with Python on the backend. This is the code I’m using …

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>UDP Chat</title>
  <!-- including JQuery just to simplify things -->
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
  <script type="javascript/text">
    var chat_room_id = undefined;
    var last_received = 0;

    /**
     * Initialize chat:
     * - Set the room id
     * - Generate the html elements (chat box, forms & inputs, etc)
     * - Sync with server
     * @param chat_room_id the id of the chatroom
     * @param html_el_id the id of the html element where the chat html should be placed
     * @return
     */
    function init_chat(chat_id, html_el_id) {
        chat_room_id = chat_id;
        layout_and_bind(html_el_id);
        sync_messages();
    }

    /**
     * Asks the server which was the last message sent to the room, and stores it's id.
     * This is used so that when joining the user does not request the full list of
     * messages, just the ones sent after he logged in.
     * @return
     */
    function sync_messages() {
        $.ajax({
            type: 'POST',
            data: {id:window.chat_room_id},
            url:'/chat/sync/',
            dataType: 'json',
            success: function (json) {
                last_received = json.last_message_id;
            }
        });

        setTimeout("get_messages()", 2000);
    }

    /**
     * Generate the Chat box's HTML and bind the ajax events
     * @param target_div_id the id of the html element where the chat will be placed
     */
    function layout_and_bind(html_el_id) {
            // layout stuff
            var html = '<div id="chat-messages-container">'+
            '<div id="chat-messages"> </div>'+
            '<div id="chat-last"> </div>'+
            '</div>'+
            '<form id="chat-form">'+
            '<input name="message" type="text" class="message" />'+
            '<input type="submit" value="Say"/>'+
            '</form>';

            $("#"+html_el_id).append(html);

            // event stuff
            $("#chat-form").submit( function () {
                var $inputs = $(this).children('input');
                var values = {};

                $inputs.each(function(i,el) {
                    values[el.name] = $(el).val();
                });
                values['chat_room_id'] = window.chat_room_id;

                $.ajax({
                    data: values,
                    dataType: 'json',
                    type: 'post',
                    url: '/chat/send/'
                });
                $('#chat-form .message').val('');
                return false;
        });
    };

    /**
     * Gets the list of messages from the server and appends the messages to the chatbox
     */
    function get_messages() {
        $.ajax({
            type: 'POST',
            data: {id:window.chat_room_id, offset: window.last_received},
            url:'/chat/receive/',
            dataType: 'json',
            success: function (json) {
                var scroll = false;

                // first check if we are at the bottom of the div, if we are, we shall scroll once the content is added
                var $containter = $("#chat-messages-container");
                if ($containter.scrollTop() == $containter.attr("scrollHeight") - $containter.height())
                    scroll = true;

                // add messages
                $.each(json, function(i,m){
                    if (m.type == 's')
                        $('#chat-messages').append('<div class="system">' + replace_emoticons(m.message) + '</div>');
                    else if (m.type == 'm')
                        $('#chat-messages').append('<div class="message"><div class="author">'+m.author+'</div>'+replace_emoticons(m.message) + '</div>');
                    else if (m.type == 'j')
                        $('#chat-messages').append('<div class="join">'+m.author+' has joined</div>');
                    else if (m.type == 'l')
                        $('#chat-messages').append('<div class="leave">'+m.author+' has left</div>');

                    last_received = m.id;
                })

                // scroll to bottom
                if (scroll)
                    $("#chat-messages-container").animate({ scrollTop: $("#chat-messages-container").attr("scrollHeight") }, 500);
            }
        });

        // wait for next
        setTimeout("get_messages()", 2000);
    }

    /**
     * Tells the chat app that we are joining
     */
    function chat_join() {
        $.ajax({
            async: false,
            type: 'POST',
            data: {chat_room_id:window.chat_room_id},
            url:'/chat/join/',
        });
    }

    /**
     * Tells the chat app that we are leaving
     */
    function chat_leave() {
        $.ajax({
            async: false,
            type: 'POST',
            data: {chat_room_id:window.chat_room_id},
            url:'/chat/leave/',
        });
    }

    // attach join and leave events
    $(window).load(function(){chat_join()});
    $(window).unload(function(){chat_leave()});

    // emoticons
    var emoticons = {
        '>:D' : 'emoticon_evilgrin.png',
        ':D' : 'emoticon_grin.png',
        '=D' : 'emoticon_happy.png',
        ':\\)' : 'emoticon_smile.png',
        ':O' : 'emoticon_surprised.png',
        ':P' : 'emoticon_tongue.png',
        ':\\(' : 'emoticon_unhappy.png',
        ':3' : 'emoticon_waii.png',
        ';\\)' : 'emoticon_wink.png',
        '\\(ball\\)' : 'sport_soccer.png'
    }

    /**
     * Regular expression maddness!!!
     * Replace the above strings for their img counterpart
     */
    function replace_emoticons(text) {
        $.each(emoticons, function(char, img) {
            re = new RegExp(char,'g');
            // replace the following at will
            text = text.replace(re, '<img src="/media/img/silk/'+img+'" />');
        });
        return text;
    }  
    </script>
</head>
<body>
  <div id="chat">
  </div>

  <script type="text/javascript">
    $(window).ready(function(){
       var chat_id = 1;
       init_chat({{ chat_id }}, "chat");
    })
  </script>
</body>
</html>

When I load the page in Firefox, I get:

ReferenceError: init_chat is not defined    
init_chat({{ chat_id }}, "chat");

However, the function init_chat is clearly defined. What am I doing wrong?
I created a jsFiddle for the page.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T21:41:04+00:00Added an answer on June 15, 2026 at 9:41 pm

    This happens when you define the functions in the head part and call them, when the document is not yet initialized. Move the script part, where the initialization happens and try it out.

    Since you are using jQuery, it would also be better, if you can initialize the variables and enclose the whole script under a function and call the function inside document‘s ready state, it would probably work.

    $(document).ready(function(){
       var chat_id = 1;
       init_chat({{ chat_id }}, "chat");
       // Something wrong here. Is it really chat_id inside {{ }}?
    });
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have this code to decode numeric html entities to the UTF8 equivalent character.
I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
Basically, what I'm trying to create is a page of div tags, each has
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I am trying to render a haml file in a javascript response like so:
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I'm not entirely sure how I managed to jack this up. http://pretty-senshi.com If you

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.