Last active
June 19, 2024 06:27
-
-
Save barsv/8691d92498b313748576a733d0ad1c3d to your computer and use it in GitHub Desktop.
Demonstrates asynchronous data transfer from client-side JavaScript to a Dash server using a hidden input. The script handles button clicks, updates input via setTimeout, and logs counts on the server.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# this program shows how to pass payload from async client javascript to the server side in dash. | |
# you click on the button and the server logs the number of clicks. | |
# !pip install dash | |
import dash | |
from dash import html, Input, Output, dcc | |
app = dash.Dash(__name__) | |
app.layout = html.Div([ | |
html.Button('Click Me', id='button'), | |
# value='' is needed to prevent React warning in devTools console. | |
dcc.Input(type='text', id='hidden-input', value='', style={'display': 'none'}), | |
html.Div(id='null_output'), | |
]) | |
# setup on click event listener for the button that passes payload to the server via the hidden input. | |
app.clientside_callback( | |
""" | |
function(n_clicks) { | |
// setTimeout emulates async code. | |
setTimeout(() => { | |
window.my_counter = window.my_counter ? window.my_counter + 1 : 1; | |
var input = document.getElementById('hidden-input'); | |
// setter is needed because under the hood React is used that tracks input state. | |
var setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set; | |
setter.call(input, window.my_counter); // sets value of the hidden input. | |
input.dispatchEvent(new Event('input', { bubbles: true })); // bubbles is needed here. | |
}, 100); | |
} | |
""", | |
Output('null_output', 'children'), | |
Input('button', 'n_clicks'), | |
prevent_initial_call=True, | |
) | |
# listen for the events on the server side. | |
@app.callback( | |
Output('null_output', 'children', allow_duplicate=True), | |
Input('hidden-input', 'value'), # listen for the hidden input value change. | |
prevent_initial_call=True, | |
) | |
def update_output(value): | |
print(f"Server received: {value}") | |
return '' | |
if __name__ == '__main__': | |
app.run_server(debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
based on https://community.plotly.com/t/send-fake-event-from-client-side-js-to-server/49278/2