Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 !

like image 365
Tony Stark Avatar asked Nov 07 '22 03:11

Tony Stark


1 Answers

$(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);
});
like image 100
Chandan Avatar answered Nov 12 '22 19:11

Chandan