Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

364
Views
Sending data between Flask and JS using AJAX for chrome extension

I'm trying to use AJAX calls to send data back and forth between my Javascript frontend for my chrome extension and the Flask API where I plan to use my Machine Learning code.

content.js

console.log("Application GO");

function colorChanger() {
  let tweets = document.querySelectorAll("article");
  tweets.forEach(function (tweet) {
    $(document).ready(function () {
    $.ajax({
          type: "POST",
          contentType: "application/json;charset=utf-8",
          url: "/_api_call",
          traditional: "true",
          data: JSON.stringify({tweet}),
          dataType: "json"
          });
  });

    tweet.setAttribute("style", "background-color: red;");
  });
}

let timer = setInterval(colorChanger, 2000);

flask code

from flask import Flask, flash, request, redirect, url_for
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route('/_api_call', methods=['GET'])
def fake_news_detector():
    data = request.get_json()
    with open('temp.txt', 'w') as f:
        f.write(data)
    return data

Error

Uncaught ReferenceError: $ is not defined
content.js:11 (anonymous function) // which points to line -  $(document).ready(function () {

I'm new to both Javascript and Flask. Any help would be really helpful. Thanks a lot !

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

First of all you don't have jQuery installed so you can't access $ and your error

Uncaught ReferenceError: $ is not defined

is saying that. you should include jQuery in your js code in order to use $ and call ajax. just follow @scrappedcola comment and follow the instructions there to add jQuery script.

second you need to define the endpoint as POST.

@app.route('/_api_call', methods=['POST'])
over 4 years ago · Santiago Trujillo Report

0

$(document).ready and $.ajax requires jQuery

fetch and window.addEventListener works in almost all latest browsers

$(document).ready => window.addEventListener('DOMContentLoaded', function(evt) {})

$.ajax => fetch

Note: Calling $(document).ready again and again inside loop for each tweet is not a good option it will run a bunch of code again and again instead setInterval can be called once after document loading completes.

content.js

async function Request(url = '', data = {}, method = 'POST') {
  // Default options are marked with *
  const response = await fetch(url, {
    method: method, // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, *cors, same-origin
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, *same-origin, omit
    headers: {
      'Content-Type': "application/json;charset=utf-8",
      // 'Content-Type': 'application/x-www-form-urlencoded',
    },
    redirect: 'follow', // manual, *follow, error
    referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: JSON.stringify(data) // body data type must match "Content-Type" header
  });
  return response.json(); // parses JSON response into native JavaScript objects
}

console.log("Application GO");

function colorChanger() {
  let tweets = document.querySelectorAll("article");

  tweets.forEach(function (tweet) {
    let response = Request("/_api_call", {tweet});
    tweet.setAttribute("style", "background-color: red;");
  });
}

window.addEventListener('DOMContentLoaded', (event) => {
    console.log('Called once after document load');
    let timer = setInterval(colorChanger, 2000);
});
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!