I am trying to create the channels real time so they can be broadcasted and i save them in a list on the backend. I will later make sure that all the channels in the list are also put in the list but for now im trying to broadcast it real time and it doesnt show me any errors but just doesn't work when I submit the form.
Here is my index.js file:

document.addEventListener('DOMContentLoaded' ()=>{

    document.querySelector('#user').onsubmit = () =>
      const dname = document.querySelector('#dname').value;

    var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);

    var contents = document.querySelector('#loggedin').innerHTML;
    const template = Handlebars.compile(contents);

      var dis_name = localStorage.getItem('dname');

      const content = template({'disname': dis_name});
      document.querySelector('body').innerHTML = content;

     // the relevant part for this doubt

      socket.on('connect', ()=>{
        document.querySelector('form').onsubmit = ()=> {

              const cname = document.querySelector('#cname').value;
              socket.emit('create channel', {'cname': cname});


  socket.on('announce channel', data => {

      const li = document.createElement('li');
      channel= data.channel;
      li.innerHTML = `Channel created: ${channel}`;


here is my application.py file: import os

from flask import Flask, render_template
from flask_socketio import SocketIO, emit

app = Flask(__name__)
app.config["SECRET_KEY"] = os.getenv("SECRET_KEY")
socketio = SocketIO(app)

@app.route("/", methods=['POST', 'GET'])
def index():
    return render_template("index.html")

@socketio.on("create channel")
def channel(data):
    channels = []
    channel = data["cname"]
    emit("announce channel", {"channel": channel}, broadcast=True)

and here is the index.html page:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.11/handlebars.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js" integrity="sha256-yr4fRk/GU1ehYJPAs8P4JlTgu0Hdsp4ZKrx8bDEDC3I=" crossorigin="anonymous"></script>
    <script id="loggedin" type="text/template">

      <main class='conatianer'>
        <h1>{% raw -%}{{ disname }}{%- endraw %}</h1>

        <form  method='post'>
          <input type='text' id='cname'>channel Name</input>
          <button id='createc'>Submit</button>

        <ul id='channels'></ul>


    <form id="user">
      <input type="text" id="dname">Display Name</input>

  <script src="static/index.js"></script>

Also wanted to mention that all of this works except the part that involves socket. Even the socket function parts work when i implement it on the chrome javascript console.

I'm not able to figure out why this won't work... kindly help!

You must log in to answer this question.

Browse other questions tagged .