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 !
$(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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With