1

i know you can easily send form data to flask using calls like $.ajax() in jquery but what I need is a way to send data to a flask server using an element, say a <p> tag.

For example: test.html

<p data-rep='testentry' class='qtemp'>Entry00</p>
<p data-rep='testentry01' class='qtemp'>Entry01</p>

index.js

$(document).ready(function(){
    $('.qtemp').on('click',function(){
        var layout = $(this).data('rep');

        $.ajax({
            url: 'workstation',
            type: 'POST',
            data: layout
        });     
    });
});

main.py

@app.route('/workstation',methods=['GET','POST'])
def workstation(data):
    layout = data

    return render_template('station.html',target=layout)

Running This App:

  1. Doesn't render the template station.html
  2. Doesn't print the layout variable which contains the data sent (I added a print statement and it didn't work,even tried writing it to file)

What i've Tried:

  1. In index.js, replace data: layout with data: JSON.stringify(layout) then in .main.py , replace layout = data with layout = request.args.get('data').

needless to say, all of this doesn't work

NB: Using an html form is not an option

1
  • You don't have a success callback in your Ajax request, so the response is just silently ignored Commented Feb 17, 2019 at 13:32

1 Answer 1

5

You need to modify your ajax to ensure that you are receiving JSONified results from the Python route. Also, in order to store data returned from an ajax call, you must access the values by key name using flask.request.args:

In index.js:

$(document).ready(function(){
   $('.qtemp').on('click',function(){
    var layout = $(this).data('rep');
     $.ajax({
      url: "/workstation",
      type: "get",
      data: {layout: layout},
      success: function(response) {
        var new_html = response.html;
      },
     });     
  });
});

In main.py:

@app.route('/workstation')
def workstation():
  layout = flask.request.args.get('layout')
  return flask.jsonify({'html':flask.render_template('station.html',target=layout)})

Edit: you can store the value garnered from the ajax request in flask.session, and redirect to the desired page. To do so, create an additional route to save the value, and then utilize window.location.replace in the body of the ajax success function:

In index.js:

$(document).ready(function(){
  $('.qtemp').on('click',function(){
    var layout = $(this).data('rep');
    $.ajax({
      url: "/update_layout",
      type: "get",
      data: {layout: layout},
      success: function(response) {
        window.location.replace('/workstation');
      },
    });     
  });
});

In main.py

import string, random

app.secret_key = ''.join(random.choice(string.printable) for _ in range(20))
#secret_key needed for session implementation

@app.route("/update_layout")
def update_layout():
  flask.session['layout'] = flask.request.args.get('layout')
  return flask.jsonify({'success':'True'})

@app.route('/workstation', methods=['GET'])
def workstation():
  return flask.render_template('station.html',target = flask.session['layout'])
Sign up to request clarification or add additional context in comments.

8 Comments

What I want is to render a page with the layout variable as text on a ptag, and this is not doing that, this sends back the HTML contents(code) back to me
@silverhash ajax requests do not function as redirects, instead, they only return data to the current page sending the request (hence "dynamic"). To implement a pseudo-form post redirect, I added a solution whereby flask.session and an additional route serve as a means by which data can be saved across requests. In the body of the success function, a redirect is used.
I replaced my post request with a get request and turned my data to an object as you did now, the data is actually sent to flask finally..but that just about sums it up, the template is still not being rendered
@silverhash Is the page being redirected to /workstation after the click?
Yes, it is..with your edit..I can now redirect successfully but the layout variable doesn't seem to be sent to the station.HTML page, the problem now might be on my end I guess..Another thing, is the the correct way or are we hacking away here :D
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.