Utilizing Ajax.Updater in conjunction with Python to respond to requests

I am working on a Python code that generates an HTML page using a template. When a click event happens, I need to read data from an Excel file and display the results, possibly in a pop-up window. My plan is to use xlrd to read the Excel file and make an Ajax request. This request will provide the URL of a Python file that reads the Excel file's content. I have chosen to utilize Prototype's Ajax.Updater method for this task.

The purpose of Ajax.Updater is to replace the response item with the response from the Python file named display.py.

I have two questions:

  1. How do we send the response back from Python? This may be a basic question, but I couldn't find clear information on this topic. Do I need to define a function and use return to pass the response value? Should I use print or sys.stdout.write()? As a beginner, I'm unsure about the best approach. Many resources mention using json; should I implement that here? Could someone explain why it is necessary? (Apologies if this question seems naive)

  2. Is there a more efficient way to achieve my objective?

The relevant code snippet is as follows:

myprog.py

from string import Template
import webbrowser

template1 = Template(
"""
<html>
<head>
    <script type = "text/javascript" src = "\javascript\prototype.js">
    </script>
    <script>

    function displayResults()
    {
        new Ajax.Updater("response", "\display.py");
    }
    </script>
</head>
<body>
<table>
<tr>
<td id = "myid" onclick = displayResults()> $something</td>
</tr>
</table>
<p id = "response">replace this</p>
</body>
</html>
""")

d = template1.substitute(something = nothing)
f= open('filename.html','w')
f.write(d)
f.close()
webbrowser.open_new('filename.html')

This is how my Python file display.py looks like:

import sys
sys.stdout.write("Content-type: text/html")
response = "dadada"
sys.stdout.write(response)
sys.stdout.write("</br>")

I am working on a Windows platform and using Prototype version 1.7.1.

Thank you,

Megh

Answer №1

Make sure to add line separators following your headers:

import sys
sys.stdout.write("Content-type: text/html\n\n")
response = "dadada"
sys.stdout.write(response)
sys.stdout.write("</br>")

If you prefer, you can use print as it automatically includes line separators:

print "Content-type: text/html"
print
response = "dadada"
print response + '</br>'

Consider exploring micro-web frameworks like Flask, Bottle, or Pyramid if you're open to alternatives for CGI scripts; these frameworks handle most HTTP details for you.

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

Failure to trigger a follow-up function in webSQL transaction's success callback

Review the code below. I have called setQuestion() within the successCallBack of db.transaction but am encountering an error: Uncaught TypeError: this.setQuestions is not a function. Can you spot any issues in my code? game.module( "game.scenes.scene" ) ...

What methods can I use to minimize the duration of invoking the location.reload() function?

When I'm using window.location.reload() in my onClick() function, it's taking too long to reload. I tried modifying the reload call to window.location.reload(true) to prevent caching, but it's still slow. The issue seems to be with location. ...

Transform basic list into a two-dimensional array (grid)

Picture a scenario where we have an array: A = Array(1, 2, 3, 4, 5, 6, 7, 8, 9); We aim to transform it into a 2-dimensional array (a matrix of N x M), similar to this representation: A = Array(Array(1, 2, 3), Array(4, 5, 6), Array(7, 8, 9)); It's ...

Getting JSON object string in Node.js using Express

I am currently utilizing Polymer's <iron-ajax> to send data, in the form of a JSON string created using JSON.stringify, to a Node Express server. However, upon receiving the data, it appears in a strange format that I am unable to parse. Specifi ...

Steps for preventing a button from being enabled until all mandatory fields are completed

Is it possible to have a button disabled until all required fields are filled out, with the button appearing grey in a disabled state and changing color when all fields are completed? I am facing an issue where clicking on the previous button is causing ...

Setting the initial state with an undo action in React: a step-by-step guide

Is it possible to display a snackbar with an undo action when dragging and dropping events in a react-big-calendar? https://i.stack.imgur.com/QFmYA.png I am trying to implement functionality where clicking on the undo action will revert the event back to ...

Is there a way to modify an npm command script while it is running?

Within my package.json file, I currently have the following script: "scripts": { "test": "react-scripts test --watchAll=false" }, I am looking to modify this script command dynamically so it becomes: "test&qu ...

Tips for minimizing the influence of external code in Next.js

What steps can I take to minimize the impact of third-party code on my next.js app? I have incorporated Google Analytics and Google AdSense on my website, but it is causing performance issues. view this illustration _document.js import Document, { Html, ...

Three.js - Model is unable to cast shadows

Greetings! I am currently diving into the world of three.js and utilizing react-three-fiber to integrate it with React. However, I've encountered a challenge regarding shadow casting between models. Despite setting obj.castShadow = true and obj.receiv ...

How to retrieve the width of a document using jQuery?

Having a strange issue with determining the document width using $(document).width() during $(window).load and $(window).resize. The problem arises when the browser is initially full screen and then resized to a narrower width, causing content to require ...

How to Append Data to an Empty JSON Object in Angular

I have started with an empty JSON object export class Car {} After importing it into my component.ts, I am looking to dynamically add fields in a loop. For example: aux = new Car; for (var i = 0; i < 10; i++) { car.addName("name" + i); } My aim is ...

Do you think there is a more efficient way to solve this issue?

const [active, setActive] = React.useState(["active", "", "", "", ""]);``your unique text`` const hrefs = React.useMemo( () => ["/", "/about", "/skills", "/projects", "/contact"], [] ); React.useEffect(() => { setInterval(() => { ...

Ways to retrieve the name of a JValue object

I have been working with Newtonsoft.Json to parse Json text, and I am trying to find a way to retrieve the name of a JToken or JValue object. For example, if "ChoiceId":865 is the value, I need to extract "ChoiceId". Despite spending hours on it, I haven&a ...

Please send a solitary email in accordance with the guidelines provided by Weblesson

I am a newcomer to the world of programming, on a quest to discover how to send a single email rather than bulk emails as demonstrated in the Web lesson tutorial that I came across (link here: 'How to Send Bulk Email in PHP using PHPMailer with Ajax J ...

Is it possible to guarantee that the initial AJAX request finishes before the next request is made?

I am working on a project that involves making consecutive async ajax calls to populate user schedules in an HTML table using jQuery. Each response returns a JSON serialized DataSet containing information about scheduled events and user details. The issue ...

"Struggling to retrieve extensive JSON data from the server efficiently with the PHP Volley library due to time-consuming processes

During the development of my app, I encountered an issue with syncing data from a PHP server using the Volley library. When the JSON response from PHP is small, everything works fine. However, problems arise when the JSON response is very large. I am curre ...

Unable to establish API connection in node.js

As a novice, I recently delved into the world of APIs using node.js. My goal was to fetch data from a simple API for practice. This venture is just an experiment and any assistance or guidance on connecting to APIs, especially those requiring an API key, ...

The TypeScript error "File 'XXX' is not recognized as a module" is preventing successful compilation

Is there a way to import a module from an external file into another TS file? Even after following the steps, when I tried to do so in VSCode, it gave me an error saying that the file 'XXX' is not a module: Here's the error I encountered I ...

Switch the state of a variable using the emit function

I need to change the value of the 'visualizacao' variable to true when a button in another component is clicked. COMPONENT 1 containing the visualizacao variable <template> <div> <card-patrimonial v-if="!visu ...

What could be the source of the "Uncaught Error: write after end" error occurring in my test cases?

Below is the code I am working with: var Promise = require('bluebird'); Promise.longStackTraces(); var path = require('path'); var fs = Promise.promisifyAll(require('fs-extra')); var clone = require('nodegit').Clone ...