This question already has answers here:
jQuery posting JSON
(3 answers)
Submit a form using jQuery [closed]
(22 answers)
Closed 5 years ago.
I have read several postings on different examples for passing a javascript variable to flask through post/get forms. I still don't understand how to do this. From my understanding, the form creates a post/get that can then be called and received by the python flask script. Can someone write up a very simple example on what this should look like?
Starting from creating a variable with any value in javascript and then making the post/get. Lastly what should the receiving end on python should look like and finally print the variable from python.
How I did this was using an ajax request from the javascript which would look something like this. I think the easiest way would be using JQuery as well since it might be a bit more verbose with pure javascript.
// some movie data
var movies = {
'title': movie_title,
'release_date': movie_release_date
}
$.ajax({
url: Flask.url_for('my_function'),
type: 'POST',
data: JSON.stringify(movies), // converts js value to JSON string
})
.done(function(result){ // on success get the return object from server
console.log(result) // do whatever with it. In this case see it in console
})
Flask.url requires JSGlue which basically let's you use Flask's
url_for but with javascript. Look it up, easy install and usage. Otherwise I think you could just replace it with the url e.g '/function_url'
Then on the server side you might have something like this:
from flask import request, jsonify, render_template
import sys
#app.route("/function_route", methods=["GET", "POST"])
def my_function():
if request.method == "POST":
data = {} // empty dict to store data
data['title'] = request.json['title']
data['release_date'] = request.json['movie_release_date']
// do whatever you want with the data here e.g look up in database or something
// if you want to print to console
print(data, file=sys.stderr)
// then return something back to frontend on success
// this returns back received data and you should see it in browser console
// because of the console.log() in the script.
return jsonify(data)
else:
return render_template('the_page_i_was_on.html')
I think the main points are to look up ajax requests in jquery, flask's request.json() and jsonify() functions.
Edit: Corrected syntax
Related
This question already has answers here:
How do I post form data with fetch api?
(11 answers)
Fetch: POST JSON data
(17 answers)
Get the data received in a Flask request
(23 answers)
Closed 2 years ago.
I'm new using flask or JS, as that, I can't find a way to do what I want to.
I created a webserver using flask (in python) and it uses index.html as main page, I wanted to update data to the server every few secounds (maybe 1-3 secs). The thing is, I don't have any form to work with, or even queries and I don't know what else can I work with. The data I want to send is small string to be saved on server host later on.
<body>
<center>
<button onmousedown="sendDirectionKey('^')">^</button>
...
</center>
</body>
<script>
function sendDirectionKey(Key)
{
...
sendData(data_string);
}
function sendData(data)
{
...
}
</script>
An easy modern solution is the fetch() API:
function sendData(data)
{
const body = new FormData();
body.append("key", data);
return fetch("/receive", {method: "POST", body, credentials: "include"});
}
The equivalent receiver on the Python side would be something like
#app.route("/receive", methods=["POST"])
def receive():
print(request.form) # should have a `key` key
This question already has answers here:
Pass JavaScript variable to Flask url_for
(3 answers)
Closed 5 years ago.
$("#getVerification").click(function () {
var tmp=$("#cellphone").val();
console.log(tmp);
$.getJSON("{{ url_for('auth.sendsms', cellphone=tmp )}}",
function(data){
});
});
as the code above, I want to use the string variable tmp as a parameter in function url_for, but I can't figure out how,
Thanks A Lot!
You can't pass javascript variables to Jinja2 because of the way the template gets rendered.
Server side processing is done before client side.
Here is the order.
Jinja2 processes the template into proper markup.
The browser parses the markup into DOM and renders it.
The way this works only allows for passing Jinja2 variables to Javascript.
You need to do without using url_for Jinja2 directive and build your URL client side.
var tmp=$("#cellphone").val();
console.log(tmp);
$.getJSON(["<url_path for auth.send_sms>", tmp].join("/"),
function(data){
});
I am not sure if I worded my question correctly. I'm not actually sure how to go about this at all.
I have a site load.html. Here I can use a textbox to enter an ID, for example 123, and the page will display some information (retrieved via a Javascript function that calls AJAX from the Flask server).
I also have a site, account.html. Here it displays all the IDs associated with an account.
I want to make it so if you click the ID in account.html, it will go to load.html and show the information required.
Basically, after I press the link, I need to change the URL to load.html, then call the Javascript function to display the information associated with the ID.
My original thoughts were to use variable routes in Flask, like #app.route('/load/<int:id>') instead of simply #app.route('/load')
But all /load does is show load.html, not actually load the information. That is done in the Javascript function I talked about earlier.
I'm not sure how to go about doing this. Any ideas?
If I need to explain more, please let me know. Thanks!
To make this more clear, I can go to load.html and call the Javascript function from the web console and it works fine. I'm just not sure how to do this with variable routes in Flask (is that the right way?) since showing the information depends on some Javascript to parse the data returned by Flask.
Flask code loading load.html
#app.route('/load')
def load():
return render_template('load.html')
Flask code returning information
#app.route('/retrieve')
def retrieve():
return jsonify({
'in':in(),
'sb':sb(),
'td':td()
})
/retrieve just returns a data structure from the database that is then parsed by the Javascript and output into the HTML. Now that I think about it, I suppose the variable route has to be in retrieve? Right now I'm using AJAX to send an ID over, should I change that to /retrieve/<int:id>? But how exactly would I retrieve the information, from, example, /retrieve/5? In AJAX I can just have data under the success method, but not for a simple web address.
Suppose if you are passing the data into retrieve from the browser url as
www.example.com/retrieve?Data=5
you can get the data value like
dataValue = request.args.get('Data')
You can specify param in url like /retrieve/<page>
It can use several ways in flask.
One way is
#app.route('/retrieve/', defaults={'page': 0})
#app.route('/retrieve/<page>')
def retrieve():
if page:
#Do page stuff here
return jsonify({
'in':in(),
'sb':sb(),
'td':td()})
Another way is
#app.route('/retrieve/<page>')
def retrieve(page=0):
if page:
#Do your page stuff hear
return jsonify({
'in':in(),
'sb':sb(),
'td':td()
})
Note: You can specify converter also like <int:page>
I've built a php API that provides data in json output, I need to get the values via a get request to then plot as a graph on the page.
The front end web component in hosted on the same server as in the api in this basic structure:
index.php
graph.php
/api/
/api/src
/api/src/api.php
My current code in graph.php is as follows:
<script>
var myJson;
$.getJson('api/src/api.php/poll/results/current/13/', function(jd){
myJson = jd.AnswerCount.1;
});
document.getElementById('jsonhere').innerHTML = myJson; //just to test
</script>
The endpoint outputs data like the following:
{"AnswerCount":{"1":5,"3":1,"2":2,"4":1,"5":5,"6":3,"7":2}}
Which I need loaded into a key-value pair array,
1:5
3:1
2:2
4:1
...
to then be put into the graphing library.
How do I fix my code/write new code to do this? I'm pretty stuck here.
EDIT:
On a hunch I logged all the get requests via wireshark, and no request is ever sent to the url in question. Even with an empty function { } ? http://grab.kfouwels.com/pmgW
You can't use a number as an identifier, to access the 1 property you have to say [1] not .1
You have to use the variable containing your data, not x which hasn't been mentioned until you try to assign it somewhere
The A in Ajax stands for Asynchronous. You have to work with your data inside your callback since the function you pass to getJson won't be called until the HTTP response arrived but the line starting document.get will run as soon as the HTTP request has been sent.
i have a problem regarding the responseXML of ajax..
I have this code from my callback function:
var lineString = responseXML.getElementsByTagName('linestring')[0].firstChild.nodeValue;
However, the linestring can only hold up to 4096 characters max.. the remaining characters are rejected.
I dont know what to use to get all the values that the lineString
returns. its quite a big data thats why I thought of using the responseXml
of AJAX, BUT turned out it still cannot accomodate everything.
My linestring consists of lines from a logfile which I concatenated and just
put line separator. I need to get this data in my form so that is why after reading from the php, i send it back via AJAX
Do you have suggestions guys.
XML adds a lot of extra markup for most ajax requests. If you are expecting some kind of list with data entities, sending them in a JSON format is the way to go.
I used JSON to get quite huge arrays with data.
First of all, JSON is just Javascript Object Notation meaning that the Ajax Request would request a String which will actually be evaluated as a Javascript object.
Some browsers offer support for JSON parsing out of the box. Other need a little help. I've used this little library to parse the responseText in all webapps that I developed and had no problems with it.
Now that you know what JSON is and how to use it, here's how the PHP code would look like.
$response = [
"success" => true, // I like to send a boolean value to indicate if the request
// was valid and ok or if there was any problem.
"records" => [
$dataEntity1, $dataEntit2 //....
]
];
echo json_enconde($response );
Try it and see what it echos. I used the php 5.4 array declaration syntax because it's cool! :)
When requesting the data via Ajax you would do:
var response
,xhr = getAjaxObject(); // XMLHttp or ActiveX or whatever.
xhr.open("POST","your url goes here");
xhr.onreadystatechange=function() {
if (xhr.readyState==4 && xhr.status==200) {
try {
response = JSON.parse(xhr.responseText);
} catch (err) {
response = {
success : false,
//other error data
};
}
if(response.success) {
//your data should be in response
// response.records should have the dataEntities
console.debug(response.records);
}
}
}
Recap:
JSON parsing needs a little help via JSON2 library
PHP can send maps as JSON
Success boolean is widely used as a "successful/unsuccessful" flag
Also, if you're into jQuery, you can just set the dataType : "json" property in the $.ajax call to receive the JSON response in the success callback.