What I Am Trying To Do: Receive data from AJAX to Flask. Eventually, I would like to send token data (Which will come from stripe) to the flask side
The Problem: I can't print any data to the console. So I'm assuming data is not being passed through.
I am unable to receive data from my Ajax call. I have been searching for some time now and I haven't found a fix. I've seen multiple different solutions for others but none of them worked for me. I'm am trying to implement a custom Stripe payment flow.
What I plan to do eventually is to pass in all the data I need (in the token) through the 'data' parameter in JSON format. Here are the different sides of code
index.html
var handler = StripeCheckout.configure({
key: 'test_key',
image: 'image_url',
locale: 'auto',
token: function(token) {
$.ajax({
url: '/charge',
data: {
'token': '(data im trying to access/print in app.py)'
},
type: 'POST',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log("ERROR");
console.log(error);
},
dataType: "json",
contentType: "application/json"
});
}
});
app.py
from flask import Flask, request
import json
#app.route('/charge', methods=['POST'])
def charge():
# Grab token information
token = request.form['token']
# The line below never prints to console
print(token)
# This test print statement below never prints to console
print("This print statement never runs")
Nothing prints to the console. I've wasted so much time on this so any leads or pointers would be greatly appreciated!
UPDATES
I did some updates suggested by #Daniel Roseman but nothing at all prints to the console.
Try the following code
In javascript:
var data = {token: token}
$.ajax({
url: '/charge',
data: JSON.stringify(data),
type: 'POST',
success: function (response) {
console.log(response);
},
error: function (error) {
console.log("ERROR");
console.log(error);
},
dataType: "json",
contentType: 'application/json;charset=UTF-8',
});
In controller [charge method]:
from flask import Flask
from flask import render_template, request, jsonify
#app.route('/charge', methods=['POST'])
def charge():
# Grab token information
token = request.json['token']
# This is the expected token from json
print(token)
# This test print statement below now prints to console
print("This print statement now runs surely")
# return JSON
return jsonify(
code=0,
msg="Success"
)
You're not posting JSON.
Instead of accessing request.get_json(), you can just access the individual elements from the request.form dictionary. In this case:
token = request.form['token']
Related
I want to create an api using python and flask that fetches data in regular time interval(10 sec) from a continuously increasing database where data is continuously coming and stored.I don't want to fetch the old data which were already fetched.
Say you currently have an API endpoint that returns all the database stored data:
#app.route('/data', methods=['post'])
def data():
all_the_data = Data.query.order_by(Data.created.desc()).all()
return jsonify(results=all_the_data)
So your ajax call currently doing something like:
$.ajax({
type: "POST",
url: "/data",
dataType: "json",
success: function(data) {
console.log(data);
update_graph(data);
}
});
You just need a way for the system to filter what's going out, back to the client-- so we instead of querying all the data, we can filter based on a reference:
#app.route('/data', methods=['post'])
def data():
client_data = request.json
reference = client_data.get('reference')
if reference:
# we have a reference, so lets filter the query:
query_data = Data.query.filter(Data.id>reference).order_by(Data.created.desc()).all()
else:
# no reference, so send the lot!
query_data = Data.query.order_by(Data.created.desc()).all()
return jsonify(results=query_data)
Then your ajax request needs to get the last reference from the last query it did-- and supply that to the API endpoint:
$.ajax({
type: "POST",
url: "/data",
data: JSON.stringify({ reference: 999 }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
console.log(data)
update_graph(data["results"]);
}
});
So you just need to work out how to get that reference value from the last set of values you recieved (the API could send that back as another key, or you could poll your current set within javascript, etc).
I have a jQuery Jtable in the front end and I am using python flask in my server.
I used python flask to fetch data from the MYSQL server which I can view in the JSON format in my browser but, unfortunately I couldn't able to make the JSON data into the Jtable.
My front end jQuery Jtable is
$('#eventsummary').jtable({
actions: {
listAction: function (postData) {
return $.Deferred(function ($dfd) {
$.ajax({
url: '/backend/groupdata',
type: 'GET',
data: postData,
success: function (data) {
$dfd.resolve(data);
console.log("loading ");
},
});
});
}
},
fields: {
irs_type: {
title: "Date & Time",
list: true,
}
}
});
$('#eventsummary').jtable('load');
and this is the error I am getting
I am also able to view my console.log code in the browser, with no error in the console.
Can someone please help me with this
Thanks,
I achieved this by using python jsonify to add my json data to the front end Jtable.
for result in data:
json_data.append(dict(zip(row_headers,result)))
return jsonify(
{
'Result': "OK",
'Records': json_data,
}
)
Thanks
The output you are seeing is the standard jTable application error. Your listAction has passed the server response to jTable, so there is no communications error.
When the json response does NOT contain Result = 'OK' it displays the application error dialog, and shows the json Message in the dialog.
The very fact that the error dialog appears means jTable is not seeing Result = 'OK' in your server response. Look for that first, if you are still stuck please post your json response. The dialog is blank because there is no error message or jTable can't see it.
I'm trying to send array as a parameter to the api which is using python and django framework.
Here's my client side code that is being used to access the api:
$.ajax(
type: 'POST',
url: 'http://example.com/api/users',
data: {user:{name:'Rohit Khatri', age:20, father_name:'S.K'},type:'info'},
complete: function(response) {
console.log(response);
}
);
Here's the view where I'm trying to access the request parameters
def get_users(request):
print(request.POST.get('ids'))
and when I try to access ids parameter, It gives None.
If anyone has faced the same problem, please help me.
You can try getting the list as follows:
request.POST.getlist('ids[]')
Note: You will be better off if you send/receive your data as JSON. You first need to set the Accept and Content-Type headers to application/json while sending the request and then convert the json to python object using json.loads. Example as follows:
Javascript/AJAX
$.ajax(
type: 'POST',
url: 'http://example.com/api/users',
contentType: 'application/json'
data: {ids:[1,2,3,4,5],type:'info'},
complete: function(response) {
console.log(response);
}
);
Django
import json
def get_users(request):
ids = request.POST.get('ids')
if ids:
ids = json.loads(ids)
Update:
In case you need to use more complicated data such as an object (dictionary) using json will be your best bet and it will work pretty similar to the above example.
Javascript/AJAX
$.ajax(
type: 'POST',
url: 'http://example.com/api/users',
contentType: 'application/json'
data: {ids:{"x":"a", "y":"b", "z":"c"}, type:'info'},
complete: function(response) {
console.log(response);
}
);
Django
import json
def get_users(request):
ids = request.POST.get('ids')
if ids:
ids = json.loads(ids)
I am trying to do a JSON post to my Bottle server.
from bottle import request, route, run
#route('/feedback', method='POST')
def feedback():
data = request.json
print data
run(host='localhost',port=8080)
In the client side, I have
$('#user_feedback').submit(function() {
var feedback = {"id": 1}
$.ajax({
type: "POST",
url: "http://localhost:8080/feedback",
data: feedback
});
return false;
});
I am returning false here because I don't want the page to be redirected.
However, the data I received in my Bottle server is always None when printed out.
Please help. Thank you.
request.json expects the content type of the request to be application/json .
So to make it work, you should set the contentType property of your request to application/json and stringify your data :
$.ajax({
type:"POST",
contentType: "application/json",
url:"/feedback",
data: JSON.stringify(feedback)
});
I have a Chrome Extension which sends data to Google App Engine(webapp2).
chrome.extension.onMessage.addListener(function (message, sender, sendResponse) {
if (message.paragraphs_ready) {
$.ajax({
url: 'http://my_website.appspot.com/',
type: 'POST',
data: {'paragraphs_ready': message.paragraphs_ready},
contentType: "application/x-www-form-urlencoded",
//dataType: 'json',
success: function(){
alert("Server received my data");
}
});
}
});
GAE(webapp2) processes data and should send a response back to Chrome Extension. I don't want to go for Channel Python API if possible.
class DataProcessing(webapp2.RequestHandler):
"""This Handler is responsible for the Processing"""
def post(self):
to_be_processed = cgi.escape(self.request.POST['paragraphs_ready'])
def my_proc(to_be_processed):
return to_be_processed
self.response.write(my_proc(to_be_processed)
success function on ajax request is called when the server responds not when the client sends a request.
So in your case you would have something like this:
success: function(data){
alert("Server received my data AND sent a response");
alert(data);
}
success: A function to be called if the request succeeds. The function
gets passed three arguments: The data returned from the server,
formatted according to the dataType parameter; a string describing the
status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of
jQuery 1.5, the success setting can accept an array of functions. Each
function will be called in turn.
See more here: http://api.jquery.com/jquery.ajax/