From my simple Streamlit contact form, I want to catch name, email and message and using JavaScript to send them to the owner of the website through FormSubmit. This is my code:
import streamlit as st
from streamlit.components.v1 import html
form = st.form("myForm", clear_on_submit=True)
name = form.text_input("Full name")
email = form.text_input("Email Address")
msg = form.text_area("Message")
submit = form.form_submit_button("Send")
my_js = """
var dict_values = {"{{name}}", "{{email}}", "{{msg}}"};
var s = JSON.stringify(dict_values);
console.log(s);
window.alert(s);
$.ajax({
method: 'POST',
url: 'https://formsubmit.co/ajax/my-email',
dataType: 'json',
accepts: 'application/json',
data: JSON.stringify(s)
success: (data) => console.log(data),
error: (err) => console.log(err)
});
"""
my_html = f'''<script src="https://code.jquery.com/jquery-3.6.1.js"></script>
<script type="text/javascript">
{my_js}
</script>
'''
if submit:
html(my_html)
The code is running well, I mean the form, but nothing happens! I think my problem is the way I passed the variables to JavaScript!
To focus on the relevant part, I added the f for string format, made double-curly-brackets where I wanted the string to keep them, used single-curly-brackets where I was inserting a Python variable value.
import streamlit as st
from streamlit.components.v1 import html
name='a'
email='b'
msg='c'
my_js = f'''
var dict_values = {{"{name}", "{email}", "{msg}"}};
'''
my_js
I tried your solution, but it doesnât work. When I added the f for string format, I got Unresolved reference 'method'error in the ajax call. If I remove the method: 'Post', url below get the same error.
I understand your double-curly-brackets- or single-curly-brackets-solution or even str(name)âŚetc.
Why you choose to add the f for string format?
Edit: I changed the method: Post to type: Post, but I still get the error: ValueError: Invalid format specifier in <module> my_js = f'''
The f tells Python you will be formatting the string with variable values inserted from code where you have curly braces. (Youâve got the f prefix on your second string, which tells Python you are inserting the my_js string where you have {my_js}.)
Did you correct the other instance of the curly braces? Youâll need to double them up. Otherwise, Python with see the single curly brace and âbreak outâ of the string, trying to read whatâs next as Python it needs to parse and insert into the string. Hence it trips over the next word method and doesnât know what to do.