Sunday, 20 December 2020

Sending data between Flask and JS using AJAX

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 !



from Sending data between Flask and JS using AJAX

No comments:

Post a Comment