Sending information to a Flask application using AJAX

Currently, I am working on transferring URLs from an extension to a Flask app. The extension is able to access the current URL of the website. I have set up an AJAX request to connect to Flask, and the connection is successful. However, when trying to send the URL to Flask, the "test" page keeps outputting a value of "None."

When users use this extension, they enter a specific website. My goal is for the extension to automatically send the URL of the website to Flask. How can I properly format the code to return the current URL to Flask while using this extension? Ultimately, I want the test page to display the user's current URL.

main.py: Within the Flask file, there is a function called testfn() where I attempt to retrieve the request data.

app = Flask(__name__)

@app.route('/test/', methods=["GET","POST"])
def testfn():
    data = request.get_json()
    return render_template("index.html", **locals())


@app.after_request
def add_headers(response):
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
    return response

index2.html: In this part, I aim to display the value of the retrieved data. However, the page consistently shows a value of "None." I want to be able to show the actual URL instead of "None."

<!doctype html>
<html>
    <body>
        <p>{{data}}</p>
    </body>
</html>

popup.js: This section involves successfully fetching the current URL of the website in the extension and sending an AJAX request.

chrome.tabs.query({active: true, lastFocusedWindow: true}, tabs => {
    var link = "";
    link = tabs[0].url;
    link = JSON.stringify(link);
    $.ajax({
        type: "POST",
        url: "http://localhost:5000/test/",
        contentType: "application/json",
        data: link,
        success: function(response) {
            console.log(response);
        },
        error: function(err) {
            console.log(err);
        }
    });   
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Associate text with a color from a predetermined list (JavaScript)

As I work on adding tags to my website for blog posts, I have a specific vision in mind. Each tag should be assigned a unique background color selected from a predefined array of theme colors. My goal is to assign the same background color to tags with id ...

Update the records and refresh the dropdown menu with the new array using AJAX

Current Situation: Using Laravel 4.2, I have a form that includes a select box. {{ Form::select('NameCustomary', $ent) }} The select box is pre-populated with persons' names. In the controller: $ent = array('' => 'Choose ...

Utilizing the setState method within an 'async function with arguments' for handling onClick events

In my next.js app, I have a file named "temp.js" located in the /pages directory. This is the code inside temp.js: import React from 'react'; import {Button} from '@mui/material'; class SomeClass extends React.Component{ state={ ...

Cease processing ajax requests on the server side

After conducting thorough research on the topic of canceling ajax requests, I have come across several threads discussing this matter. One particular thread caught my attention: Abort Ajax requests using jQuery The post explains how when you use the abor ...

Using Jquery, Json, and PHP for Dynamic Web Applications

Hey there! I'm currently working on a post form in jQuery with PHP. The form calls another page and retrieves the result as JSON from jQuery. For example, when I use jQuery to call a PHP page, I receive the following JSON data: <?php print '{ ...

Identical IDs appearing in multiple buttons causing a conflict

I am currently loading content from external HTML files, specifically page1.html and page2.html. Although everything is the same except for the pictures and text, I am encountering an issue with the close button. It only closes page1.html.Feel free to chec ...

What is the best way to compare a string with a specific object key in order to retrieve the corresponding value?

I'm looking to achieve a relatively simple task, or at least I think so. My goal is to compare the pathname of a page with key-value pairs in an object. For example: if("pathname" === "key"){return value;} That's all there is to it. But I&apos ...

What is the best way to transfer a string to a different Vue component?

Within my project, I have a masterData.js file that serves as a repository for my master data. This file retrieves data from my mongo db and distributes it to various components of the project. To facilitate this process, I have implemented a function with ...

Transform JSON information into a CSV layout

Is there a simple method to convert the JSON format provided below into CSV? JSON { "item1" : { "status":"Shipped", "Location":"TX", "trackingno":"z123345df234" }, "item2" : { "status":"OrderReceived", "Location":"AZ", "trackingno":"D234235 ...

Customizing the DatePicker with a unique button in material-ui

For my current project, I am utilizing a Datepicker component. I am looking to incorporate a custom information button in the upper right corner of the calendar layout, similar to the example image provided below: https://i.stack.imgur.com/fHMbn.png Unfo ...

Error message: Error in jQuery: Object is required for Internet

I have a button that is designed to trigger the opening of a jQuery UI Dialog when clicked. Strangely, it works perfectly in FF3, FF4, Chrome, and IE8 with ChromeFrame, but fails to function in regular IE8. The error message displayed simply states "Object ...

Having trouble accessing a JSON file in OpenShift using Python?

Having an issue with my Python code running on Openshift. I'm trying to access a JSON-formatted text file on a subdomain of my app. from flask import Flask from flask import render_template import json app = Flask(__name__) @app.route("/") def ind ...

After clicking in the Firefox browser, the Window.open function is unexpectedly showing [object Window]

I have added an anchor link that, when clicked, opens a new window with the specified link. Below is the code I used for this purpose: <a href="javascript:window.open('https://www.remax.fi/fi/kiinteistonvalitys/tietosuojaseloste/', &apos ...

Encountering issue while converting XML to JSON on Android platform

Attempting to retrieve data from the Earthquake API. Utilizing Retrofit for this task, fetching data in XML format and successfully converting it to JSON using an XML-JSON Converter Library. The library functions correctly with simple XML strings like: & ...

Steps for capturing a screenshot of the canvas while utilizing the react-stl-obj-viewer component

I recently started using a component called react-stl-obj-viewer to display a 3D STL image. The rendering of the image itself is working fine. However, I encountered an issue when trying to move the rendered image around and implement a button for capturin ...

Using ReactJS and Hooks to update state after the .map() function

Trying to update the state using values from an array. Here is an example: const [state, setState] = useState({}); const test = [1, 2, 3]; test.map((item, i) => { setState({ ...state, [`item-${i}`]: item }); }); The current s ...

Converting basic text into JSON using Node.js

Today I am trying to convert a text into JSON data. For example: 1 kokoa#0368's Discord Profile Avatar kokoa#0000 826 2 Azzky 陈东晓#7475's Discord Profile Avatar Azzky 陈东晓#0000 703 3 StarKleey 帅哥#6163's Di ...

The failure of the Selenium script can be attributed to the presence of the AJAX

Struggling to automate an application with an AJAX loader causing issues? Getting the dreaded error message about element not being clickable when the loader is active? Frustrating, right? But fear not! I have devised a clever solution in the form of a wr ...

Enhance Bootstrap typeahead to accommodate multiple values

I have a basic typeahead setup for searching city names. However, upon selecting a city, I also need to retrieve its latitude and longitude in order to send that data to the backend. $('.typeahead').typeahead({ minLength : 3, source : ...

Attempting to cast org.json.simple.JSONArray to org.json.simple.JSONObject is not possible

I'm currently facing an issue while trying to process a file for POSTing JSON data into a local platform that requires an access token. I keep encountering the following error: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject. D ...