Having trouble transferring data from Flask to JavaScript as JSON when using a separate .js file

In my templates/index.html file, I have the following code:

<!DOCTYPE html>
<html lang="en">
<head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <style>

    </style>
</head>
<body>
    <div id="graphDiv"></div>

    <script src="http://d3js.org/d3.v3.min.js"></script>
    <script type="text/javascript" src="{{ url_for('static', filename='main.js') }}"></script>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
    <script>

    </script>
</body>
</html>

In my app.py file, I have the following code:

import json

from flask import Flask, render_template
import pandas as pd

app = Flask(__name__)

@app.route("/")

def index():
    df = pd.read_csv('data.csv').drop('Open', axis=1)
    chart_data = df.to_dict(orient='records')
    chart_data = json.dumps(chart_data, indent=2)
    data = {'chart_data': chart_data}
    return render_template("index.html", data=data)


if __name__ == "__main__":
    app.run(debug=True, host="0.0.0.0", port =5000)

I decided to move the JavaScript code from the index.html file into a separate directory named static/, where I stored the style.css and main.js files containing the following code:

var graphData = {{ data.chart_data | safe }}

var margin = {top: 30, right: 50, bottom: 30, left: 50};
var svgWidth = 600;
var svgHeight = 270;
var graphWidth = svgWidth - margin.left - margin.right;
var graphHeight = svgHeight - margin.top - margin.bottom;

// More JavaScript code here...

drawGraph(graphData);

However, when running the Flask server, I encountered an error:

SyntaxError: expected property name, got '{'
in the line
var graphData = {{ data.chart_data | safe }}
. The strange thing is that this error only occurs when the JavaScript code is not inline in the index.html file. I've tried researching solutions but haven't been able to fix the issue. It's still unclear to me why this error is happening.

Answer №1

<!DOCTYPE html>
<html lang="en">
<head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <style>

    </style>
</head>
<body>
    <div id="graphDiv"></div>

    <script src="http://d3js.org/d3.v3.min.js"></script>
    <script type="text/javascript">
      var chartData = {{ data.chart_data | safe }}
    </script>
    <script type="text/javascript" src="{{ url_for('static', filename='main.js') }}"></script>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</body>
</html>  

The issue is occurring because the code contains Jinja2 templating syntax instead of valid JavaScript syntax.

You must ensure to define the variable chartData before utilizing it in your main.js file.

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

Error: This Service Worker is restricted to secure origins only due to a DOMException

Having trouble implementing this on my website; it keeps showing the following error. Help, please! Service Worker Error DOMException: Only secure origins are allowed. if ('serviceWorker' in navigator && 'PushManager' in wind ...

What is the ideal Java interface for efficiently reading and writing XML and JSON data?

In search of a user-friendly interface to convert Objects to and from their XML or JSON String representations, I have come up with the following: public interface IStringifier{ /** Converts the Object to it's String representation, e.g. XML or J ...

Initially, the OWL Carousel image is not displaying correctly due to incorrect sizing

I am currently working with OWL Carousel and have implemented a code that displays one image at a time, with the next image sliding in every 15 seconds. The width is set to occupy 100% of the screen and I have configured the JavaScript accordingly so that ...

Combine Rest API with JSON into BPMN for React or Angular 8 along with TypeScript compatibility

Looking for an angular or react BPMN library that supports TypeScript and REST API services without needing to parse XML. I've searched extensively but can't find a BPMN library with JSON service. I need to create a workflow similar to this us ...

Animating Text Around a Circle Using HTML5 Canvas

Can someone please help me figure out what is wrong with this code? It's not rotating as it should, and the text looks messed up. I've been trying to solve this problem for hours but can't seem to get it right. function showCircularNameRot ...

In Visual Studio, make sure to include a reference to AngularJS.min.js within another JavaScript file

In my AngularJS app, I am utilizing Visual Studio with separate folders. The AngularJS-min.js file is located in a different folder. My query is how can I correctly reference the AngularJS-min.js file in my app's JavaScript file to enable auto-suggest ...

Press the designated button located within a table's td element to retrieve the values of adjacent td elements

I need to implement a functionality where clicking a button within a <td> element will retrieve the values of other <td> elements within the same row (<tr>). Here is the current implementation: $(document).ready(function(){ ...

Struggling to display the preloader animation while waiting for the render.com server to start up (using the free tier web service)

My choice for deploying dynamic websites is render.com and I am currently using their free tier. The issue with this free service is that Render spins down the web service after 15 minutes of inactivity, resulting in a delay when it needs to spin back up u ...

The request body for MERN full stack development is returning empty

I am currently facing an issue while trying to establish a connection between my client and the backend. Here is the snippet of code I am using: //client const body = { email: value, }; axios.get("http://localhost:5000/checkEmail", body) // ...

What is the best way to interpret a nested JSON object?

Recently I've crafted an object that looks like this. myObj = { "name":"John", "age":30, "cars": [ "car1":"Ford", "car2":"BMW", "car3":"Fiat" ] } While it's pretty straightforward to read the name and age properties, I find ...

Is there a way to first run my validate function and then proceed with sending my AJAX request upon clicking a button?

Hey there! I've got a dynamic table generated from a database. You can check out the table. I have all the necessary code in place, but what I really need is to ensure proper timing of execution for specific actions: 1) Verify if all mandatory fields ...

Vuex action method completes without returning a value

I've come across a situation in my Vuex action where the console.log() is displaying an undefined output. Here's the method in my Vuex action: const actions = { async fetchByQuery({ commit, title }) { console.log(title); //other code ...

Ensure the JSON object has a specific data type

I need to validate JSON data that includes a type value. I have created a case class called SearchRequestMessage along with a companion object that contains a JSON writer. The value T can either be a Long or a UUID. case class SearchRequestMessage[T](jobI ...

What are the steps to achieve consistent response behavior in POSTMAN that matches that of a web browser?

Below is an example of my code: const express = require('express'); const app = express(); app.get('/', function (req, res) { res.setHeader('Content-Type', 'text/html'); res.write("First \n"); set ...

Why is it that vanilla HTML/JS (including React) opts for camelCase in its styling conventions, while CSS does not follow the same pattern

Each type of technology for styling has its own set of conventions when it comes to naming properties, with camelCase and hyphenated-style being the two main options. When applying styles directly to an HTML DOM Node using JavaScript, the syntax would be ...

Experiencing Limitations with Node.JS node-hbase Scan Functionality, Unable to Retrieve More than 1000

I am facing an issue while trying to retrieve records from an HBase table in Node.JS using the node-hbase module, which connects to the rest server. I am able to fetch the first batch of records successfully, but I am struggling to get the next set of re ...

Tips for evaluating an array of objects in JavaScript

Welcome to the world of coding! Here's a scenario with an array: [ { "question1": "Apple", "question2": 5, "question3": "Item 1" }, { "question1": ...

AngularJS: How do I stop the $interval from running indefinitely?

After spending hours reading the documentation, it's now 3am and I'm at my wit's end. Below is my controller code: controller('makeDashCtrl', function ($scope, $rootScope, $cookies, $location, $http, $interval) { var userId ...

Fading in and out occurs several times while scrolling through the window

My goal is to update the logo image source with a fadeIn and fadeOut effect when scrolling up or down. The issue I'm facing is that the effect happens multiple times even after just one scroll, resulting in the logo flashing many times before finally ...

Does the unique identifier of the element remain constant in jQuery?

For example: $("#savenew").live('click', function(e) { var user=<?php echo $user?>; $.ajax({ type: "POST", url: "actions/sub.php", data:{user: user} , ...