ChatIQ
ContactSolutionsDocsBlogDashboard
Sign inSign up
ContactSolutionsDocsBlogDashboard
Sign inSign up
ChatIQ

Build reliable AI chatbots powered by your team’s knowledge. Secure multi-tenant architecture, instant document ingestion, and guided analytics out of the box.

Product
How it worksFeaturesDemo
Resources
SolutionsBlogDocsContactDashboard
Legal & Preferences
Terms of ServicePrivacy PolicySecurityDPA
© 2026 ChatIQ. All rights reserved.Made with care in distributed workspaces worldwide.

Basic Chat Integration Example

Simple example of integrating ChatIQ chatbot with basic JavaScript and HTML.

Basic Chat Integration Example

A minimal example showing how to integrate ChatIQ chatbot into any website using vanilla JavaScript.


Overview

This example demonstrates:

  • Simple HTML/CSS/JavaScript implementation
  • Basic message sending and receiving
  • Conversation state management
  • Error handling

Best for: Simple websites, landing pages, quick prototypes


Step 1: HTML Structure

Create a basic HTML page with a chat interface:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>ChatIQ Basic Example</title>
  <style>
    .chat-container {
      max-width: 600px;
      margin: 50px auto;
      border: 1px solid #ddd;
      border-radius: 8px;
      overflow: hidden;
      box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }
    .chat-messages {
      height: 400px;
      overflow-y: auto;
      padding: 20px;
      background: #f9f9f9;
    }
    .message {
      margin-bottom: 15px;
      padding: 10px;
      border-radius: 8px;
    }
    .message.user {
      background: #007bff;
      color: white;
      text-align: right;
    }
    .message.assistant {
      background: white;
      border: 1px solid #ddd;
    }
    .chat-input {
      display: flex;
      padding: 15px;
      background: white;
      border-top: 1px solid #ddd;
    }
    .chat-input input {
      flex: 1;
      padding: 10px;
      border: 1px solid #ddd;
      border-radius: 4px;
      margin-right: 10px;
    }
    .chat-input button {
      padding: 10px 20px;
      background: #007bff;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
    }
    .chat-input button:disabled {
      background: #ccc;
      cursor: not-allowed;
    }
  </style>
</head>
<body>
  <div class="chat-container">
    <div class="chat-messages" id="messages"></div>
    <div class="chat-input">
      <input type="text" id="messageInput" placeholder="Type your message...">
      <button id="sendButton" onclick="sendMessage()">Send</button>
    </div>
  </div>

  <script>
    // Configuration
    const API_URL = '/api/chatbot'; // Your backend proxy endpoint
    let conversationId = null;

    // Send message function
    async function sendMessage() {
      const input = document.getElementById('messageInput');
      const button = document.getElementById('sendButton');
      const message = input.value.trim();
      
      if (!message) return;

      // Add user message to UI
      addMessage('user', message);
      input.value = '';
      button.disabled = true;

      try {
        const response = await fetch(API_URL, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            message: message,
            conversation_id: conversationId,
          }),
        });

        if (!response.ok) {
          throw new Error('Failed to send message');
        }

        const data = await response.json();
        
        // Update conversation ID
        if (data.conversationId) {
          conversationId = data.conversationId;
        }

        // Add assistant response to UI
        addMessage('assistant', data.response || 'No response received');
      } catch (error) {
        addMessage('assistant', 'Sorry, something went wrong. Please try again.');
        console.error('Error:', error);
      } finally {
        button.disabled = false;
        input.focus();
      }
    }

    // Add message to chat UI
    function addMessage(role, content) {
      const messagesDiv = document.getElementById('messages');
      const messageDiv = document.createElement('div');
      messageDiv.className = `message ${role}`;
      messageDiv.textContent = content;
      messagesDiv.appendChild(messageDiv);
      messagesDiv.scrollTop = messagesDiv.scrollHeight;
    }

    // Allow Enter key to send
    document.getElementById('messageInput').addEventListener('keypress', (e) => {
      if (e.key === 'Enter') {
        sendMessage();
      }
    });
  </script>
</body>
</html>

Step 2: Backend Proxy (Required)

Create a backend endpoint to proxy requests to ChatIQ (keeps your API key secure):

Node.js/Express Example

// server.js
const express = require('express');
const app = express();

app.use(express.json());

app.post('/api/chatbot', async (req, res) => {
  const { message, conversation_id } = req.body;

  try {
    const response = await fetch('https://chatiq.io/api/chat', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${process.env.CHATIQ_API_KEY}`,
      },
      body: JSON.stringify({
        message: message,
        bot_slug: process.env.CHATIQ_BOT_SLUG,
        stream: false,
        conversation_id: conversation_id || null,
      }),
    });

    const data = await response.json();
    res.json(data);
  } catch (error) {
    res.status(500).json({ error: 'Failed to communicate with ChatIQ' });
  }
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});

Python/Flask Example

# app.py
from flask import Flask, request, jsonify
import os
import requests

app = Flask(__name__)

@app.route('/api/chatbot', methods=['POST'])
def chatbot():
    data = request.json
    message = data.get('message')
    conversation_id = data.get('conversation_id')

    response = requests.post(
        'https://chatiq.io/api/chat',
        headers={
            'Content-Type': 'application/json',
            'Authorization': f'Bearer {os.getenv("CHATIQ_API_KEY")}',
        },
        json={
            'message': message,
            'bot_slug': os.getenv('CHATIQ_BOT_SLUG'),
            'stream': False,
            'conversation_id': conversation_id,
        }
    )

    return jsonify(response.json())

if __name__ == '__main__':
    app.run(port=3000)

Step 3: Environment Variables

Create a .env file for your backend:

CHATIQ_API_KEY=sk_live_your_api_key_here
CHATIQ_BOT_SLUG=your-bot-slug

Step 4: Customization

Add Loading Indicator

function addMessage(role, content) {
  const messagesDiv = document.getElementById('messages');
  const messageDiv = document.createElement('div');
  messageDiv.className = `message ${role}`;
  messageDiv.textContent = content;
  messagesDiv.appendChild(messageDiv);
  messagesDiv.scrollTop = messagesDiv.scrollHeight;
}

function showLoading() {
  const messagesDiv = document.getElementById('messages');
  const loadingDiv = document.createElement('div');
  loadingDiv.id = 'loading';
  loadingDiv.className = 'message assistant';
  loadingDiv.textContent = 'Thinking...';
  messagesDiv.appendChild(loadingDiv);
}

function hideLoading() {
  const loading = document.getElementById('loading');
  if (loading) loading.remove();
}

// Update sendMessage function
async function sendMessage() {
  // ... existing code ...
  showLoading();
  
  try {
    // ... fetch code ...
    hideLoading();
    addMessage('assistant', data.response);
  } catch (error) {
    hideLoading();
    addMessage('assistant', 'Sorry, something went wrong.');
  }
}

Add Message Timestamps

function addMessage(role, content) {
  const messagesDiv = document.getElementById('messages');
  const messageDiv = document.createElement('div');
  messageDiv.className = `message ${role}`;
  
  const time = new Date().toLocaleTimeString();
  messageDiv.innerHTML = `
    <div>${content}</div>
    <small style="opacity: 0.7; font-size: 0.8em;">${time}</small>
  `;
  
  messagesDiv.appendChild(messageDiv);
  messagesDiv.scrollTop = messagesDiv.scrollHeight;
}

Next Steps

  • Add streaming support for real-time responses
  • Implement React components for more complex UIs
  • Add conversation history persistence
  • Customize styling to match your brand

Full Working Example

See a complete working example on CodePen or JSFiddle.

Note: Remember to set up your backend proxy endpoint before testing. Never expose your API key in client-side code.