I have a JavaScript function that generates buttons for seats
and each seat
gets an hx-post
, hx-trigger
, and hx-params
. In the params, the seat id (for example "0-0" or "12-5") is generated. I want to get the params in the POST request /select_seat
and print it. My code returns "None"
JS:
const seat = document.createElement("button");
seat.innerHTML = `${(c + 1) + (r * 6)} - ${(ic + 1) + (ir * 8)}`;
seat.setAttribute("hx-params", `${(c + 1) + (r * 6)}-${(ic + 1) + (ir * 8)}`);
seat.setAttribute("hx-trigger", 'click');
seat.setAttribute("hx-post", '/select_seat');
Htmx:
<button hx-params="1-1" hx-trigger="click" hx-post="/select_seat" class="seat">1 - 1</button>
Flask:
@app.route('/select_seat', methods=['POST'])
def your_route():
print(request.data) # Print the raw data received
htmx_data = request.json
if htmx_data:
hx_params = htmx_data.get('params', {}).get('hx-params', None)
if hx_params:
print(hx_params)
return jsonify({'status': 'success'})
return jsonify({'status': 'error'})
See the Flask code above.
2
Answers
hx-params
is not used to pass values, but to filter specific inputs to be sent, or not, with the request.What you are looking for is
hx-vals
https://htmx.org/attributes/hx-vals/Try this:
Then you can read the
seat
value in your post request.The code you provided for the Flask server-side isn’t going to be able to access the
hx-params
attribute in the POST request. Thats because HTMX sends the parameters as part of the request body or as query parameters.In your JavaScript, you need to define how
hx-params
is supposed to be sent. For example, you can change your code to:Then, on the server-side in Flask, you can access this parameter using: