Refresh the page with user input after a button is clicked without reloading the entire page, using Python Flask

My python/flask web page accepts user input and returns it back to the user without reloading the page. Instead of using a POST request, I have implemented Ajax/JavaScript to handle user input, process it through flask in python, and display the result to the user.

While I am able to successfully process user input in python, I am facing difficulties updating the web page with the returned information.

I currently have functioning code that utilizes a POST request, but for my project, I prefer to avoid page reloads and simply update the content on the page.

*.py

@app.route('/t')
def pre():
    tx = request.args.get('aa')
    print('input',tx)
    return render_template('test.html',tx=tx)

*.html

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
  <script type=text/javascript>
    $(function() {
      $('a#cal').bind('click', function() {
        $.getJSON('/t', {
          aa: $('input[name="text"]').val(),
        }, function(data) {
          $('#result').html('<img src="data:image/png;base64,' + data.result + '" />');
          });
        return false;
      });
    });
  </script>
  <form>
    <input type="text" size="5" name="text">
     <span id="result">
         <p>For the love of god: {{tx}}</p>
        </span>
        <a href="javascript:void();" id="cal">calculate server side</a>
    </form>

Answer №1

This is an example of how your code should be structured:

*.py

from flask import render_template, jsonify

@app.route('/test')
def test():
    return render_template('test.html')


@app.route('/t')
def pre():
    tx = request.args.get('aa')
    print('input:', tx)
    data = {"result": tx}
    return jsonify(data)

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

Ionic, Angular - A component with two out of three inputs displaying undefined values

I am facing an issue with the @input() in my code. Two out of three inputs have undefined values when I try to use them, although they can be displayed using interpolation in the template file. .ts : export class NoteCanvasPageComponent { @Input() note ...

Expressjs Error- ReferenceError: cors has not been defined in this context

While working on creating a backend using ExpressJs, I encountered an error when running the backend. app.use(cors()) ^ ReferenceError: cors is not defined at Object.<anonymous> (C:\Users\hp\Desktop\Entri\kanba\ ...

The ChromeDriver detects when the Chrome browser is launched

When attempting to use selenium chromedriver in Python for the website www.mouser.co.uk, it is immediately flagged as a bot. Does anyone have an explanation for this? Below is the code I am utilizing: https://i.stack.imgur.com/g3uLP.png options = Options ...

Tips for transferring data from Express to .ejs file during redirection in Node.js

When I submit the login form in my login.ejs file, the page redirects if the details are correct. If the password is wrong, however, I want to display a message in the .ejs file indicating this. Below are the details: Here is the code in my app.js file - ...

Tips for applying a class to two elements when a checkbox is clicked and avoiding duplicated URL strings

Issue with Checkbox Selection In my project, I have implemented two tabbed containers for grid and list view. Each container contains multiple elements called info boxes with checkbox inputs. Whenever a checkbox is checked, the background color of the res ...

Discovering the summation of chosen options multiplied by input fields with the assistance of jQuery

I am attempting to calculate the average for different subjects and print it immediately whenever the user modifies a value. To input the marks, I am using input fields and corresponding select options for the hours allotted to each subject. I can accura ...

The JSON data in CRM 2011 is displaying as undefined, but the URL is still showing the

I have been struggling with a simple odata query where the call is successful, but I keep getting undefined results. I've tried various methods to inspect the object, but it still shows undefined. What could be causing this issue? UPDATE: After some ...

Track the amount of time visitors spend on my website with the help of AJAX

Looking for assistance with my Ajax script. I'm trying to track and record the amount of time a visitor spends on my website, then send that data to a PHP page: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">< ...

Looking for assistance with a simple Javascript program

My program needs to have a for loop and utilize existing input functions (name and number). Additionally, I need to calculate totals. Users should be able to CANCEL and proceed to doc.write where they can enter their name and number. Furthermore, users s ...

Leveraging orWhere in the bookshelf JavaScript object

I encountered an issue while using bookshelf js to create a query. When implementing orWhere in the query, I received an error message. An error occurred stating 'Object has no method 'orWhere'." Below is the code snippet that led to thi ...

What is the best way to call a JavaScript function with multiple arguments from a Silverlight project?

I encountered an issue when trying to invoke a JavaScript function with multiple arguments from an HTML page. Here is what I am attempting to do: wbNavigator.Navigate(new Uri("http://localhost:56433/route.html", UriKind.Absolute)); object results = wbNavi ...

Modifying the appearance of radio buttons using jQuery

I'm new to jQuery and I'm finding it challenging. Currently, I have a set of three radio buttons with the third button already prechecked. My aim is to change the CSS class of the checked button, making it similar to an unchecked button with the ...

Placing a div over a JavaScript element

Is it feasible to overlay a div(1) with a background image on top of another div(2) that contains JavaScript (like Google maps API v3)? I have experimented with z-index without success, and I am unable to utilize absolute positioning because I depend on t ...

Generate a fresh Date/Time by combining individual Date and Time components

I have set up a form to gather dates from one input box and times from another. var appointment_date = new Date(); var appointment_start = new Date("Mon Apr 24 2017 20:00:00 GMT-0400 (EDT)"); var appointment_end = new Date("Mon Apr 24 2017 21:30:00 GMT- ...

Utilizing ES6 imports with module names instead of paths

Is there a way to import modules using just their name without the full path? For instance, can I simply use: import ViewportChecker from 'viewport-checker'; instead of import ViewportChecker from '../ViewportChecker'; I'd ...

Calculate and retrieve the result from the event handling function

I need to capture a returned value and store it in a variable within an event handler function. Below is a sample code snippet demonstrating this: var xhr = new XMLHttpRequest(); function getData(e) { if (xhr.readyState === 4) { if (xhr.s ...

Generate a compressed file from a readable source, insert a new document, and transfer the output

The objective is to obtain an archive from the client, include a file, and transfer it to Cloud Storage without generating a temporary file. Both the client and server utilize the archiver library. The issue with the code snippet provided is that the file ...

NodeJs Importing a File

Currently working with NodeJS, I have encountered a challenge. Is it possible to require a JavaScript file in Node similar to how we do in browsers? When using the require() method, I noticed that the JavaScript file called does not have access to global v ...

What causes the disparity in the functionality of getServerSideProps between index.js and [id].js in NextJS?

Exploring NextJS and React as part of my e-commerce site development journey has been exciting. However, I encountered a roadblock when trying to connect to an external database that requires real-time updates, making getStaticProps unsuitable for my needs ...

Is there a way to stop all HTML5 videos except for the one that I want to watch?

On my webpage, I have three HTML5 videos all on one page. My goal is to be able to pause or mute all the videos at once, except for the one that I specifically choose. Initially, I tried using an event listener on the parent div which worked well when clic ...