AJAX Post Request to Python Flask [duplicate] - javascript

This question already has answers here:
How do I write JSON data to a file?
(16 answers)
Closed 5 years ago.
Trying to understand how to send post requests to my backend (flask).
In my HTML I have 3 checkboxes and a submit button. My submit button returns a javascript array and I'm trying to send that javascript array to an api endpoint 'api/regions' which you can see below.
$(document).ready(function() {
$("#loadData").click(getChecked);
});
function getChecked() {
event.preventDefault();
var checkboxes = $(".form-check input[type=checkbox]:checked");
//toArray: convert checkboxes object to javascript array
var labels = checkboxes.toArray().map(checkbox => checkbox.value);
$.ajax({
url: 'api/regions',
type: "POST",
data: JSON.stringify(labels),
processData: false,
contentType: "application/json; charset=UTF-8",
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
}
In my app.py I have a route for my endpoint api:
#app.route('/api/regions', methods=['POST'])
def regions():
regions = request.json
with open("C:\\test.txt", 'w') as f:
f.write(regions)
if __name__ == "__main__":
app.run(debug=True)
I understand there is no return statement, I'm just trying to write the data I get from
regions = request.json
to a file. "C:\test.txt"
The error I'm getting when trying to do this is 500 which doesn't give me a lot to work with. I'm not sure if what I'm missing is on the front end or back end so hopefully someone could shed some light on where I'm going wrong.

From the flask documentation,
If the mimetype is application/json this will contain the parsed JSON data. Otherwise this will be None.
The key there is that .json is the parsed JSON data, not the original string. If you want to write it to a file, you'll need to convert it back to a string it first, perhaps by using json.dumps():
with open("C:\\test.txt", 'w') as f:
f.write(json.dumps(regions))

Related

Passing a list data from html to python (flask)

I passed a list data selectedOrder from python to html as below.
return render_template(f"fillForm.html", items=selectedOrder)
I know there is a way to send a single data from html either by using input form or appending data to url as in /fillForm?sid=3&quantity=5 but I'm curious if I can send a list data from html back to python in such a manner as well. Obviously I can just store the data to some variable within python before passing it but given how my code is working, it would be better to directly get the data from html if possible. Not sure if this will matter, but I use flask and jinja2 template.
You could use an ajax request and send your list as a json. Flask provides the method request.get_json() to retrieve the json data received as a dict. Assuming you have jquery it would be like:
$.ajax({
url: "/your_route",
type: "POST",
contentType: "application/json;charset=UTF-8",
dataType: "json",
data: JSON.stringify({html_data: yourlist}),
success: function(response) {
console.log(response);
},
});
Then on flask side:
#app.route('/your_route')
def your_route():
data = request.get_json()
print(data['html_data']) # should print your list
# don't forget to return a success status

Receive data with flask and send data with jQuery [duplicate]

This question already has answers here:
How do I get the different parts of a Flask request's url?
(4 answers)
jQuery posting JSON
(3 answers)
How to get POSTed JSON in Flask?
(13 answers)
Closed 4 years ago.
!! THIS IS NOT A DUPLICATE !!
The question was not how to get an URL in Flask, but how to send data with jQuery to Flask!
I try to send and receive data with python, Flask and jQuery
The problem is that I want the full URL of the website and it is impossible to get it with flask because I make 'POST' requests. So with jQuery, I want to send the current URL.
I don't know how to send data (with jQuery) and receive data (with Flask).
Python/Flask code:
#app.route('/invisible', methods = ['POST'])
def dynamic_refresh():
return jsonify({'somedata': 'data'})
HTML/jQuery code:
<script>
$(document).ready(function() {
window.setInterval(function() {
$.ajax({
type : 'POST',
url : '/invisible',
//I tried to send data from here but it didn't worked
})
.done(function(data) {
console.log(data)
console.log(window.location.href)//the url I want to send
//here I use the data received by the server
})
}, 5000);
});
</script>
Its quite simple, enclose data in JSON array which you want to send through POST request and then retrieve any data from Flask endpoint like this;
var url = $('#url').val().trim(); //get your value from HTML here
var params = {
_url: url,
};
var array = JSON.stringify(params); //enclosed it in json array
$.ajax({
type: "POST",
url: "/invisible",
data: array,
dataType: 'json',
success: function(results){
console.log(results)
}
});

Python Flask not receiving AJAX post? [duplicate]

This question already has answers here:
Get the data received in a Flask request
(23 answers)
Closed 5 years ago.
I have run into a problem with my javascript/python script. What I am trying to do is pass a string to python flask so I can use it later. When I click the button to send the string, there are no errors but nothing happens. I am basically a self taught coder so I apologise if my script it not properly formatted!
Javascript:
$('#button').click(function() {
$.ajax({
url:"/",
type: 'POST',
data: data,
...
Python Flask:
from flask import Flask
from flask import request
from flask import render_template
app = Flask(__name__)
#app.route('/', methods=['POST', 'GET'])
def home():
if request.method == "POST":
string = request.args.get(data)
print(string)
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
I want to be able to see the string printed to either the console or the command prompt, I assume print() is the right way to do this?
Any help would be welcome, thank you :)
You can make an ajax POST request like this:
$.ajax({
url: "/",
method: "POST",
data: { paramter : value },
});
The data send over this POST request can be accessed in flask app withrequest.form['parameter']
If you are sending raw json data, you can access the data by request.json['parameter']
$.ajax({
url: "/",
method: "POST",
data: JSON.stringify("{'paramter': 'value'}"),
contentType: 'application/json;charset=UTF-8'
});
And this should work.
What you want is in request.data.
request.args contains parameters in the URL.
Check this out for more details. http://flask.pocoo.org/docs/0.11/api/#incoming-request-data
If you data object in Ajax is json then you can use request.get_json()
If it is form data of key value then you can request.form.get('data') but your ajax should be
$('#button').click(function() {
$.ajax({
url:"/",
type: 'POST',
data: {data: 'mystring'},

AJAX Post to store JSON with Python and javascript

I have been having problems with getting AJAX to post JSON correctly. The application is intended to be hosted on Google App Engine. But what I have does not post data.
Python
mainPage = """
<html>
html is included in my python file.
</html>
"""
class JSONInterface(webapp2.RequestHandler):
def post(self):
name =self.request.get('name')
nickname =self.request.get('nickname')
callback = self.request.get('callback')
if len(name) > 0 and len(nickname) >0:
newmsg = Entry(name=name, nickname=nickname)
newmsg.put()
if len(name)>0:
self.response.out.write(getJSONMessages(callback))
else:
self.response.out.write("something didnt work")
def get(self):
callback = self.request.get('callback')
self.response.out.write(getJSONMessages(callback))
This handler is meant to handle the Ajax calls from the web app. I am unsure if I need javascript to be associated with my main page in order to do so, as I haven't found information on it yet with my searches.
Javascript
$(document).ready( function() {
$("#post").bind('click', function(event){
var name = $("#name").val();
var nickname = $("#nickname").val();
postData = {name: name, nickname: nickname, callback: "newMessage"};
$.ajax({
type: "POST",
url: "http://localhost:27080/json",
data: postData,
dataType: "json",
done: function() {
// Clear out the posted message...
$("#nickname").val('');
},
fail: function(e) {
confirm("Error", e.message);
}
});
// prevent default posting of form (since we're making an Ajax call)...
event.preventDefault();
});
The Javascript for the post
Can someone advise me on how I could resolve the problem I am having. Thanks for the time and help.
Did you ask the same question yesterday and then delete it? I swear I just answered the same question.
You're not sending your data as a JSON string. If you want to send as JSON, you need to encode data as a JSON string, or else you're just sending it as a query string.
data: JSON.stringify(postdata),
HOWERVER, your request handler is actually processing the request properly as query string instead of JSON, so you probably don't want to do that.
For starters, the ajax call is pretty close. The full path
"http:://localhost:27080/json"
is not necessary, the relative path will work, but that is not the problem.
Your callback, as it stands, will work as 'success':
success: function(response) {
alert(response);
// Clear out the posted message...
$("#nickname").val('');
}
However, this callback is being phased out in favor of other methods. 'Done' should be chained like so:
$.ajax({
type: "POST",
url: "/json",
data: postData,
dataType: "json"
}).done(function(data){
console.log(data);
});
Also, there might be problems on the server. If you use some logging, you will see that the data is indeed being sent to the server.
import json ## we'll get to this below
import logging
class JSONInterface(webapp2.RequestHandler):
def post(self):
name = self.request.get('name')
logging.info(name) ## will print the value of 'name'
Unless your python function getJSONMessages(callback) is returning a json object, your callback will not be called, even after you add the response parameter.
In your python code:
import json
import logging
class JSONInterface(webapp2.RequestHandler):
def post(self):
callback = self.request.get('callback')
logging.info(callback) # will print correctly
self.response.out.write(json.dumps(callback))
Using the json.dumps method encodes the passing object to json, which is what your ajax object is looking for.

Passing variables between Python and Javascript

Imagine that you need to write some Javascript that simply changes a set of checkboxes when a drop down list is changed.
Depending on which item is selected in the list, some of the checkboxes will become checked/unchecked.
In the back, you have Python code along with some SQLAlchemy.
The Javascript needs to identify the selected item in the list as usual, send it back to the Python module which will then use the variable in some SQLAlchemy to return a list of checkboxes which need to be checked i.e. "User selected 'Ford', so checkboxes 'Focus', 'Mondeo', 'Fiesta' need to be checked"
The issue Im having is that I cant seem to find a way to access the python modules from the Javascript without turning a div into a mini browser page and passing a url containing variables into it!
Does anyone have any ideas on how this should work?
Funny, I've got web pages with JavaScript that talk to Python CGI modules that use SQLAlchemy.
What I do is send AJAX request but with JSON request in the body instead of XML. Python CGI modules use standard json module to deserialize JSON into a dictionary.
JavaScript side looks like this:
function on_request_success(response) {
console.debug('response', response);
}
function on_request_error(r, text_status, error_thrown) {
console.debug('error', text_status + ", " + error_thrown + ":\n" + r.responseText);
}
var request = { ... };
jQuery.ajax({
url: 'http://host/whatever.cgi',
type: 'POST',
cache: false,
data: JSON.stringify(request),
contentType: 'application/json',
processData: false,
success: on_request_success,
error: on_request_error
});
And Python like this:
request = json.load(sys.stdin)
response = handle_request(request)
print("Content-Type: application/json", end="\n\n")
json.dump(response, sys.stdout, indent=2)
Note, it doesn't use Python cgi module, since the whole request is passed as JSON in the body.
python has a json module, which is a perfect fit for this scenario.
using a good old AJAX, with json as the data format will allow you to exchange data between javascript and your python module.
(unless your python module is running on the client side, but then i don't see how you could execute it from the browser...)
Ajax is a good way to pass variables between python and javascript.
Javascript:
param = {a:'hello', b: 'world', c: '!'}
$.ajax({
type: "post",
url: "scpi.py",
cache: false,
async: 'asynchronous',
dataType: 'html',
data: param,
success: function(data) {
console.log(data)
},
error: function(request, status, error){
console.log("Error: " + error)
}
})
Server.py: (You will need a three functions for this to work)
def do_POST(self):
if "scpi.py" in self.path:
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD': 'POST'}
)
a = form['a'].value
b = form['b'].value
c = form['c'].value
content = myfunction(a, b, c)
self.respond(content)
def handle_http(self, data):
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
print(data)
return bytes(str(data), 'UTF-8')
def respond(self, data):
response = self.handle_http(data)
print(data)
FYI: "myfunction(a, b, c,)" is a function from another python file, then return the data and passes to self.respond to send back to javascript

Categories