Displayed data disappears after successfully adding data to sqlite database
01:26 01 Dec 2025

Please help me! I'm building a simple stock search app using Flask (backend) and plain HTML/JS (frontend). When the user enters a ticker, the app:

Send a GET request to my Flask backend (/search)

Display the stock data returned from the Tiingo API

After successful display, send a POST request to /add_to_history to store the ticker in a SQLite database

The GET request works correctly — the data displays as expected in my table.

The problem: As soon as the POST request (/add_to_history) returns a 200 response, the table that was displaying the fetched stock data immediately disappears from the page. There are no errors in the console, and both network requests return status 200. The UI simply hides the content right after the POST call finishes. Here is my index.html code



  
    
    
    
    Stock App
    
  
  
    

Stock Search

Enter Stock Ticker Symbol*

Here is the app.py file

from flask import Flask, request, jsonify
from flask_cors import CORS
import requests
import sqlite3
app = Flask(__name__)
CORS(app, resources={r"/search*": {"origins": "*"}, r"/add_to_history*": {"origins": "*"}})
API_KEY = "SECRET_API_KEY"
DB_NAME = "search_history.db"
@app.route('/')
def index():
  return "Hello, World!"


def init_db():
    with sqlite3.connect(DB_NAME) as conn:
        conn.execute('''CREATE TABLE IF NOT EXISTS SearchHistory (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            ticker TEXT NOT NULL,
            timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
        )''')

# initialize the database
# run init_db() when the app starts
init_db()

@app.route('/history', methods=['GET'])
def get_search_history():
  with sqlite3.connect(DB_NAME) as conn:
    conn.row_factory = sqlite3.Row
    rows = conn.execute('SELECT ticker, timestamp FROM SearchHistory LIMIT 10').fetchall()
    results = [dict(row) for row in rows]
  return jsonify(results)


@app.route('/add_to_history', methods=['POST'])
def add_to_history():
  try:
    data = request.get_json()
    if not data:
      return jsonify({'error': 'No JSON data provided'}), 400
    
    ticker = data.get('ticker')
    if not ticker:
      return jsonify({'error': 'Ticker is required'}), 400
    
    with sqlite3.connect(DB_NAME) as conn:
      conn.execute('INSERT INTO SearchHistory(ticker) VALUES (?)', (ticker,))
      conn.commit()
    
    return jsonify({'message': 'Record added to history'}), 200
  except Exception as e:
    return jsonify({'error': str(e)}), 500

def get_history():
  with sqlite3.connect(DB_NAME) as conn:
    conn.row_factory = sqlite3.Row
    rows = conn.execute('SELECT ticker, timestamp FROM SearchHistory LIMIT 10').fetchall()
    results = [dict(row) for row in rows]
  return results


@app.route('/search', methods=['GET'])
def search():
  try:
    ticker = request.args.get('ticker', "")
    # if not ticker is passed, return error message
    if not ticker:
      return jsonify({'error': "No record has been found, please enter a valid symbol" })

    # define a return object
    results = []
    # fetch company outlook tab
    url = f"https://api.tiingo.com/tiingo/daily/{ticker}?token={API_KEY}"
    response = requests.get(url)
    data = response.json()
    if data and data.get('detail', "") != "Not found.":
      results.append(data)
    # fetch stock summary tab
    url = f"https://api.tiingo.com/iex/{ticker}?token={API_KEY}"
    response = requests.get(url)
    data = response.json()
    if data and len(data) > 0:
      results.append(data[0]) 
    # add to history if fetched successfully
    # if results:
    #   add_to_history(ticker)
    
    return jsonify(results)

  except Exception as e:
    return jsonify({'error': str(e) })
  
if __name__ == '__main__':
  app.run(debug=True)

python sqlite flask