Render Jinja after jQuery AJAX request to Flask

2024/10/6 10:31:47

I have a web application that gets dynamic data from Flask when a select element from HTML is changed. of course that is done via jquery ajax. No probs here I got that.

The problem is, the dynamic data - that is sent by Flask -, is a list of objects from the database Flask-sqlalchemy.

Of course the data is sent as JSON from Flask.

I'd like to iterate through those objects to display their info using Jinja.

HTML

<select id="#mySelect"><option value="option1" id="1">Option 1 </option><option value="option2" id="1">Option 2 </option> <option value="option3" id="3">Option 3 </option>
</select>

jQuery

$('body').on('change','#mySelect',function(){var option_id = $('#mySelect').find(':selected').attr('id');$.ajax({url: "{{ url_for('_get_content') }}",type: "POST",dataType: "json",data: {'option_id':option_id},success: function(data){data = data.data;/* HERE I WANT TO ITERATE THROUGH THE data LIST OF OBJECTS */}});
});

Flask

@app.route('/_get_content/')
def _get_content():option_id = request.form['option_id']all_options = models.Content.query.filter_by(id=option_id)return jsonify({'data': all_options})

PS : I know that jinja gets rendered first so there is no way to assign jQuery variables to Jinja. So how exactly am I going to iterate through the data list if I can't use it in Jinja ?

Answer

Okay, I got it.

Simply, I made an external html file and added the required jinja template to it.

{% for object in object_list %}{{object.name}}
{% endfor %}

then in my Flask file I literally returned the render_template response to the jquery ( which contained the HTML I wanted to append )

objects_from_db = getAllObjects()
return jsonify({'data': render_template('the_temp.html', object_list=objects_from_db)}

And then simply append the HTML from the response to the required div to be updated.

Edit: Here's the link to a Youtube video that I made which explains the process: https://youtu.be/ZEv4AjvoQOk

https://en.xdnf.cn/q/70381.html

Related Q&A

shape-preserving piecewise cubic interpolation for 3D curve in python

I have a curve in 3D space. I want to use a shape-preserving piecewise cubic interpolation on it similar to pchip in matlab. I researched functions provided in scipy.interpolate, e.g. interp2d, but …

ForeignKey vs OneToOne field django [duplicate]

This question already has answers here:OneToOneField() vs ForeignKey() in Django(12 answers)Closed 9 years ago.I need to extend django user with some additional fields . I found 2 different ways there…

How to sort glob.glob numerically?

I have a bunch of files sorted numerically on a folder, when I try to sort glob.glob I never get the files in the right order.file examples and expected output sorting folder ------ C:\Users\user\Deskt…

How to determine a numpy-array reshape strategy

For a python project I often find myself reshaping and re-arranging n-dimensional numpy arrays. However, I have a hard time to determine how to approach the problem, visualize the outcome of the result…

matplotlib plotting multiple lines in 3D

I am trying to plot multiple lines in a 3D plot using matplotlib. I have 6 datasets with x and y values. What Ive tried so far was, to give each point in the data sets a z-value. So all points in data …

How to get a telegram private channel id with telethon

Hi cant figure out how to solve this problem, so any help will be really appreciated. Im subscribed to a private channel. This channel has no username and I dont have the invite link (the admin just ad…

boolean mask in pandas panel

i am having some trouble masking a panel in the same way that I would a DataFrame. What I want to do feels simple, but I have not found a way looking at the docs and online forums. I have a simple ex…

How can I move the text label of a radiobutton below the button in Python Tkinter?

Im wondering if theres a way to move the label text of a radiobutton to a different area, e.g. below the actual button.Below is an example of a few radiobuttons being placed using grid that Im using:fr…

play sound file in PyQt

Ive developed a software in PyQt which plays sound.Im using Phonon Library to play the sound but it has some lag.So how can I play a sound file in PyQt without using Phonon Library.This is how I am cur…

translating named list vectors from R into rpy2 in Python?

What is the equivalent of the following R code in Rpy2 in python?Var1 = c("navy", "darkgreen") names(Var1) = c("Class1", "Class2") ann_colors = list(Var1 = Var1…