Sending Python data as JSON to Javascript

I have a query regarding passing data from a Python database to JavaScript.

The current code allows for accessing the data in JavaScript but only one row at a time can be passed.

#!le/usr/bin/env python3
        import sys
        import re
        import datetime
        import sqlite3
        import json
        import time
        SQLDB = '/home/daylene/db/PiLN.sqlite3'
        db = sqlite3.connect(SQLDB) 
        db.row_factory = sqlite3.Row
        cursor = db.cursor()
        sql = '''SELECT segment, dt, set_temp, temp, pid_output
                   FROM firing WHERE run_id=? ORDER BY dt;
              '''
        p = ((54),)
        cursor.execute(sql, p)
        columns = [column[0] for column in cursor.description]
        results = []
        for row in cursor.fetchall():
            results.append(dict(zip(columns,row)))
        print(json.dumps(results[-1]))
    

And here is the corresponding JavaScript code:

<script>
          $(document).ready(function () {
              showGraph();
          });
  
          function showGraph()
          {
              $.ajax({
                mimeType: 'application/json; charset=iso-8859-1',
                url:  'data.cgi',
                contentType: "application/json",
                dataType: 'json',
                method: 'POST',
                async: false,
                success:  function (response)
                  {
                      var time = response["dt"];
                      var temp = response["temp"];
                      
                      var chartData = {
                          labels: time,
                          datasets: [
                              {
                                  label: 'time',
                                  backgroundColor: '#49e2ff',
                                  borderColor: '#46d5f1',
                                  hoverBackgroundColor: '#CCCCCC',
                                  hoverBorderColor: '#666666',
                                  data: temp
                              }
                          ]
                      };
  
                      var graphTarget = $("#graphCanvas");
  
                      var barGraph = new Chart(graphTarget, {
                          type: 'bar',
                          data: chartData
                      });
                  }
              });
          }
      </script>
    

If I uncomment document.write(response); and change it to print(json.dumps(results)), it doesn't work. Nothing is returned with document.write(response);.

I have tried adding this piece of code, which also did not yield the desired result:

results1 = []
        for row in results:
            results1.append(json.dumps(row))
        print(results1)
    

Following that, when I added the next snippet of code, it also did not produce the expected outcome:

results1 = []
        for row in results:
            results1.append(json.dumps(row))
        print(json.dump(results1))
    

This is the shortened output of print(results):

[{"segment": 4, "dt": "2020-07-09 19:58:55", "set_temp": 1145, "temp": 1145.02, "pid_output": 83.49}, {"segment": 4, "dt": "2020-07-09 19:59:24", "set_temp": 1145, "temp": 1145.15, "pid_output": 80.76}, ... ]

I would appreciate any guidance on how to solve this issue.

Answer №1

If you're looking to transfer data from Python to your JS frontend easily, one effective method is creating a server that can handle HTTP requests.

An example using Flask:

from flask import Flask, jsonify

app = Flask(__name__)

@app.route("/my-data")
def get_data():

    my_data = [{"segment": 4, "dt": "2020-07-09 19:58:55"}, {}]

    return jsonify(my_data)

if __name__ == "__main__":
    app.run(port=8080, host="0.0.0.0")

After setting up the server, you can access the data by making a request to http://localhost:8080/my-data from your Javascript code.

Answer №2

Well, I finally solved the issue. It turned out to be not the code itself but rather the size of the data I was attempting to transfer. Using a smaller array resolved the problem.

I decided to investigate further by checking the lighttpd logs and I came across this message:

(mod_cgi.c.588) response headers too large for /app/data.cgi

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 displaying cookies when loading in browser

Currently, I am working on building a webpage using node.js with the hbs engine and express framework. After a user logs in, I am trying to capture cookies and use them for authentication purposes on a specific page. app.get('/path', function (r ...

Issue with 1.bundle.js not loading during webpack production build with routing

I have been encountering an issue with my test repository for this specific problem (Link) It appears that the problem lies within the localization file, as I am using react-intl. The development version seems to be functioning properly. This is what&ap ...

When JQuery Ajax encounters an error

I'm facing an issue with my ajax function after setting the dataType to Json. Below is the code snippet: Ajax script: $('#da').on("change",function() { $.ajax({ url: "callAjaxIndex.php", type: "P ...

Transform the URL to retrieve JSON information

I'm facing an issue while fetching JSON data from a remote server. Everything works smoothly until I pass a two-character string, which causes my app to force stop. How can I encode the URL to avoid this error? Below is the code snippet where I attem ...

Decoding a nested struct with JSON.Unmarshal

I need assistance with unmarshaling to the struct Outer. Here is the structure definition: type Outer struct { Inner Num int } type Inner struct { Data string } func (i *Inner) UnmarshalJSON(data []byte) error { i.Data = string(data) ...

The unusual performance of NLog on our live server

After publishing my NLog configuration to the run server, I noticed a strange issue occurring. My NLog setup looks like this: "targets": { "all-file": { "type": "File", "fileName": "${var_logdir}/nlog-all-${shortda ...

How can you initialize a JavaScript class that has a member variable of its own class?

I've come across an interesting puzzle. I am creating a class that can dynamically replicate itself to different levels, similar to an expandable menu. The initial definition looks like this: class MyClass { name: string = ''; fields ...

The use of a map with Next/image seems to be preventing the src image from loading properly

Utilizing next/image for loading images in my application has been successful, except when it comes to a carousel featuring multiple images. Whenever I attempt this, I encounter the following error: Error: Image is missing required "src" property. Make su ...

Guide on changing image source using a function

I am looking to dynamically set the img src="" attribute using a JavaScript function that changes the image based on a variable and checks its values: Here is the JavaScript code in the file: function myFunctionstatus(){ var ledactual = document.getE ...

Implement Placeholder feature in ng2-ckeditor with the combination of Typescript and Angular 2.0

I am encountering an issue while trying to add the placeholder plugin to the CKEditor toolbar. When I include extraPlugins:'placeholder' in the CKEditor configuration, I receive the following error - Error: [CKEDITOR.resourceManager.load] Resou ...

The static files for the icon CSS (404 Error) from Flaticon and Font-mfizz are failing to load properly

When I was designing a website, I needed an icon of Python, so I turned to Flaticon and found what I was looking for. This snippet shows the HTML code I used: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <li ...

React-Native 0.1.17 Navigator Bar: Enhancing User Navigation Experience

An issue arose after upgrading my react-native 0.1.15 app to version 0.1.17 - I'm now encountering an 'Unable to download JS bundle error'. Upon investigation, I found the error in my code: var SportsSocial = React.createClass({ component ...

Guide on displaying two different array elements in a single TR using JSON in AngularJS

I need help with printing two arrays in a single tr. Here is the JSON data: [{"group_name":"Ecofresh","id":"19","userId":"19","device_details":[{"userid":"19","unit_id":"35","unit_name":"Test123","mac_id":"EB9F5E5727D7","m2xa":"95005c74d3cb33ca320e4b92cde ...

Is it secure to attach the password field to a data object property in Vue.js?

This particular inquiry has been bothering me lately. Imagine I aim to create a login element for my application (using Vue), containing 2 specific input fields - one for the userID and the other for the password. The focus here is on the security of the ...

Display all contacts neatly organized in a table using JSON format

I have implemented this function to fetch all my contacts from Google Contacts. session_start(); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/accounts/ClientLogin'); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); $ ...

Steps to substituting characters within a date string

Create a function called normalize that changes '-' to '/' in a given date string. For example, normalize('20-05-2017') should output '20/05/2017'. This is my attempt: let d = new Date('27-11-2021'); fun ...

How can I change the color of a designated column in a Google stacked bar chart by clicking a button?

I am in the process of creating a website that compares incoming students at my university across different academic years. We have successfully implemented a pie chart to display data for the selected year. Now, we aim to include a stacked bar chart next ...

The JSP page does not redirect after an Ajax post request has been made

When submitting a form with basic AJAX post, I am facing an issue where the redirection to the JSP does not occur upon success. Setting the redirect programmatically seems to create a new JSP instead of utilizing the existing one with POST data. After debu ...

What is the method for creating an array of strings in VueJS?

In my VueJS and Vuetify project, I am working on creating a modal that allows users to input strings into a text field. What I aim to achieve is adding the inputted string to an array when the user clicks on create button. For example, if I enter 'inp ...

The Thinkster.io MEAN Stack guide: A blank "post" appears on the homepage. What is causing this and how can I remove it?

Currently, I am immersed in the MEAN Stack tutorial provided by Thinkster.io. At this stage, I am integrating the node.js backend with the Angularjs frontend. The functionality includes data persistence for users to add posts and upvote them. However, an ...