How to send JSON from HTML link to Python Flask? [duplicate] - javascript

This question already has answers here:
Fetch: POST JSON data
(17 answers)
How to use a link to call JavaScript?
(10 answers)
Closed 3 years ago.
I have a certain JSON object already setted in my HTML code, which via Jinja2 I receive and proceed to perform actions with.
let selectedJson = {{json | safe}}
This is the way I send it in the first place:
#app.route('/pad/analizador222/', methods=['POST', 'GET'])
def analizador222():
littleJSON = {"something" : "something-else"}
mode = 1
return render_template("output.html", json = littleJSON , mode = mode )
Now, after I did some stuff with the object, I need to re-send it back to another "#app.route()" via an HTML LINK, for example:
<a>This is the link I need to click on to send the previously mentioned JSON</a>
Here's the other app.route()
#app.route('/analisis-conversaciones', methods=['POST', 'GET'])
def analisisconversaciones():
return render_template("analysis.html")
I need to do some other stuff that does not matter at the moment with that JSON in "analysis.html"
The question is:
How can I send that JSON object via a common HTML link?
I think POST protocol can help, but in that case I don't know how to use it.

Related

Bad request when trying to send data from JavaScript to a Flask Route [duplicate]

This question already has answers here:
How to get POSTed JSON in Flask?
(13 answers)
Closed 2 months ago.
I need to pass data from JavaScript to Flask Route, however when I call the uploadData() function, I always get a Bad request error (400). What could be the problem? Here is the code:
This is the simple JavaScript function:
<script>
function uploadData() {
let data = localStorage.getItem("evaluation");
const request = new XMLHttpRequest();
request.open('POST', '/uploadfile')
request.send(data);
}
</script>
<button id="test" onclick="uploadData()">Upload</button>
This is the Python Flask code:
#app.route('/uploadfile', methods=["GET","POST"])
def uploadfile():
file = request.get_json()
file.save(os.path.join(os.path.abspath(os.path.dirname(__file__)),app.config['UPLOAD_FOLDER'],secure_filename(file.filename))) # The file is saved in a folder with name in the variable "UPLOAD_FOLDER"
return "Done"
If you upload the file via a parameter, it gets passed as query string.
You need to convert your data into a file object before using the .save() method on it. There are various ways to do so - most commonly is the usage of the io library.
Just convert your file via file = BytesIO(data.encode('utf-8')) before continuing your file.save(...)!

Flask request.get_json() returning None when valid json data sent via post request [duplicate]

This question already has answers here:
How to get POSTed JSON in Flask?
(13 answers)
Closed 4 years ago.
Building an app using flask. The app uses a table structure to display data. Part of its functionality is collecting the data from user specified table rows. To do this I have placed a button on each row that executes some js. The js collects the information from the row, uses JSON.stringify() to convert to json object and the issues the post request to the relevant flask url.
Logging the value of the jsonified object to the browser console from js file shows it is correctly formed. The post request contacts the correct route however the request.get_json() function returns a value of None in the method of that route.
I have set up a seperate route in flask for testing. Here is the relevant code
from javascript
function do_some_work(e) {
var row_data = get_table_row_data(e);
row_data = JSON.stringify(row_data);
console.log(row_data);
$.post("test", row_data);
}
get_table_row_data() simply returns an object with key:value pairs. The log shows the data is correctly formatted json.
And here is the python code
#TODO
#application.route('/test', methods=['GET', 'POST'])
def test():
data = request.get_json()
print("data is "+format(data))
return redirect(url_for('index'))
Here data is coming up as None
any help much appreciated
It's request.json it will return a dictionary of the JSON data. To get a value you use request.json.get('value_name'). So your route will be like this
#TODO
#application.route('/test', methods=['GET', 'POST'])
def test():
data = request.json
print("data is " + format(data))
return redirect(url_for('index'))

render_template in Flask on JS click event [duplicate]

This question already has answers here:
replace div content using ajax and jquery
(4 answers)
How to manage a redirect request after a jQuery Ajax call
(34 answers)
Closed 5 years ago.
I am trying to call a function in Flask by clicking a button. When the button is clicked, the following script runs.
JS
$("#load_btn").click(function() {
$.get("/callback");
}
Flask
#app.route('/callback')
def callback():
print('called')
... # code here that needs to run before rendering callback
return render_template('callback.html')
The problem here is, called is printed, and GET /callback HTTP/1.1 200 is logged as well, but callback.html is not rendered - the page stays the same. I'm guessing this is probably not the best approach to solving this problem, but if so what is the recommended approach?
$.get just sends an HTTP request to your server, but doesn't actually do anything anything with the data (in your case, the rendered template) it gets back from the server.
Try something like this:
$("#load_btn").click(function() {
$("html").load("/callback");
}
Or if the template you render doesn't contain any <head> tags, only body content, you can do
$("#load_btn").click(function() {
$("body").load("/callback");
}
Or, you can exchange "body" for a specific element to only replace a specific part of the page.
If you want the user to be redirected, do this:
$("#load_btn").click(function() {
window.location = "/callback";
}

Get Json data with POST request from website API [duplicate]

This question already has answers here:
Pure JavaScript Send POST Data Without a Form
(13 answers)
Closed 6 years ago.
How can I get Json information from a website API in javascript?
I need to get quotes text from this website http://forismatic.com/en/api/ to put in my quotes generator page.
I think I kinda of get how to great GET requests, but from my understanding this API requires POST requests.
If you have any idea, could you also direct me to the explanation of the code you've written, because I'd also like to understand the underlying logic.
Thanks!
Try this.. Its already working, JSONP
function insertReply(content) {
document.getElementById('output').innerHTML = content;
}
// create script element
var script = document.createElement('script');
// assing src with callback name
script.src = 'http://url.to.json?callback=insertReply';
// insert script to document and load content
document.body.appendChild(script);

passing variable from java script to jsp script let [duplicate]

This question already has answers here:
How do I pass JavaScript values to Scriptlet in JSP?
(9 answers)
Closed 6 years ago.
I want to pass a java script var to script let in jsp.
i tried many things but not working anything.can anyone tell me a working solution.
i have tried How do I pass JavaScript values to Scriptlet in JSP?
the way this other post stays, is the correct one.
1- create an ajax call (in Javascript) in your webpage to send your desired params to another page.
2- create a page (in jsp) where you request the data sent by the #1.
That's the correct way to go.
#1 Here's an example on how to make an ajax call, you need this on step #1, if your using jquery is simple as:
String data1 = "myData1";
String data2 = "myData2";
String your_jsp_page_to_request = "myJspPage.jsp";
$.post(your_jsp_page_to_request,
{ param1: data1, param2: data2 },
function(data){
alert("Data Loaded: " + data);
}
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
#2 Then in your jsp you need to request the data sent, just using:
String data1 = request.getParameter("param1");
String data2 = request.getParameter("param2");

Categories