I want to send this variable value in python variable to perform different tasks.
var d="string"
I don't want to send variable values through URL.
I want to use some like this code.
#app.route("/", methods=['POST'])
def hello1():
d = request.form['n'] #here i take value from name of html element
use an AJAX post.
let myVar = 'Hello'
$.post('http://localhost:5000/getjs', {myVar}, function(){
// Do something once posted.
})
and your Flask will be something like this
#app.route('/getjs', methods=['POST'])
def get_js():
if request.method == 'post':
js_variable = request.form
return js_variable
Alternatively you can do this:
#app.route('/getjs/<variable>')
def get_js(variable):
js_variable = variable
return js_variable
so when you direct your url to http://localhost:5000/getjs/apples
js_variable will be 'apples'
Use native javascript 'fetch'.
Ari Victor's solution requires an external library: jquery
var url = 'http://localhost:5000/getjs';
var data = {field_name: 'field_value'};
fetch(url, {
method: 'POST',
body: JSON.stringify(data),
headers:{
'Content-Type': 'application/json'
}
}).then(res => res.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error));
Related
I have two projects, the first one is Node.JS.
jsonobj = JSON.stringify(generateMockData)
xhrToSoftware.send(jsonobj);
xhrToAPI.open("POST", "http://127.0.0.1:8000/path/", true);
xhrToAPI.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhrToAPI.send(jsonobj);
It's sending data to the second project Django Python. I can receive the data using my views.py.
post_data = json.loads(request.body.decode("utf-8"))
value = post_data.get('data')
print(value)
But I want to directly get the data from Node.JS to my Django Templates (javascript or jquery) is that possible?
for example:
<script>
//get the data that posted by the node.js
</script>
UPDATE:
I tried using the answers below like this one:
fetch('http://127.0.0.1:8000/path/')
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => console.error(error));
but I'm having an error it says that:
SyntaxError: Unexpected token '<', "<!--
<d"... is not valid JSON
I think that's because I'm returning an html file in my views.py:
def data(request):
if request.method == 'POST':
post_data = json.loads(request.body.decode("utf-8")) # for simulation
value = post_data.get('data')
return render(request, 'waterplant/iot/data.html')
so, I change it to jsonresponse like this:
def data(request):
if request.method == 'POST':
post_data = json.loads(request.body.decode("utf-8")) # for simulation
value = post_data.get('data')
return JsonResponse({"msg": value}, status=200)
After that I'm having an error ValueError: The view views.data didn't return an HttpResponse object. It returned None instead. I think that's because the value is empty yet. How can I prevent that? If I send a data using my Node.JS I want to return it as return JsonResponse({"msg": value}, status=200) Or you have any idea that I can access the data directly in my Django Python templates <script> here </script>
Basic js fetch()
If you use method "GET":
fetch('http://127.0.0.1:8000/path')
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => console.error(error));
If you use method "POST":
fetch(`http://127.0.0.1:8000/path`, {
method: "POST",
headers: {"Content-type": "application/json; charset=UTF-8"},
body: data
})
.then(response => response.json())
.then(json => {
console.log(json);
})
.catch(error => console.error('Error on fetch() call:\n', error));
Hope it could be useful!
If a get request is to be made from your webpage use fetch()
fetch('http://127.0.0.1:8000/path')
.then((response) => response.json())
.then((data) => console.log(data));
I got a question with my Django project. I have a database and want to get data into JavaScript with a fetch request. The data should just be in JSON. This was my attempt with Serializer. Is there a more easy way, than writing a whole serializer.py. Does anybody have an idea what to do.
JavaScript:
fetch('', {
method: 'GET',
})
.then(response => response.json())
.then(data => {
console.log(data);
});
DJango views.py:
def ausgeben(request):
if request.method == 'GET':
ausgeben = Schraube.objects.all()
serializer = SchraubeSerializer(schrauben, many=True)
return JsonResponse(serializer.data, safe=False)
return render(request, 'AR-Ausgeben.html', all_items)
Does anyone know how to use data that was calculated in one script in another script?
For example within head this script gets a customer email
Edit: Added var customer_email; but getting undefined when using customer_email outside of loadSuccess() function.
<script>
var customer_email;
async function loadSuccess() {
const response = await fetch('/.netlify/functions/success', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
}).then((res) => res.json())
.catch((err) => console.error(err));;
customer_email = response.session.customer_details.email;
console.log(customer_email);
}
loadSuccess();
console.log(customer_email);
}
</script>
<script>
console.log(customer_email);
</script>
Now in a different also within , how can customer_email be used?
In this example, only the 1st console.log(customer_email) within loadSuccess() prints the email. The other 2 print undefined.
Make customer_email a global variable
<script>
var customer_email;
async function loadSuccess() {
const response = await fetch('/.netlify/functions/success', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
}).then((res) => res.json())
.catch((err) => console.error(err));;
customer_email = response.session.customer_details.email;
}
loadSuccess();
}
</script>
You are able to assign your value to a global variable, such as window._customer_Email.
window._customer_Email = response.session.customer_details.email;
Then you can access this in the same way
console.log(window._customer_Email)
Note that global variables are something recommended against because they cannot be garbage collected easily and also pollute the global state (risking conflicts)
I have an application running a Flask backend with a React frontend and I'm trying to do some error handling for the front end and display the error message to the user. Here is a simplified version of my files:
Flask
#app.route('/api/download', methods=['POST'])
def download():
data = request.json
#Get data from external API via a post request here
try:
req = urllib.request.Request(url, data, headers)
with urllib.request.urlopen(req) as f:
res = f.read()
print("Success")
data = json.loads(res.decode())
df = pd.json_normalize(data['observationList'])
#Do some pandas magic here
retData = df.to_json(orient="records")
return retData
except Exception as e:
pprint(e)
return jsonify(message='password_update_error'),500
JavaScript
fetch("/api/download", {
method:"POST",
cache: "no-cache",
headers:{
'Content-Type': 'application/json'
},
body: JSON.stringify({
values: this.state.values
})
}).then((response) => response.json())
.then(data => {
this.setState({ sdata: data }, () => {
// click the CSVLink component to trigger the CSV download
setTimeout(() => {
this.csvLink.current.link.click();
});
})
}).catch(err => {
errorBox.innerHTML = "<span style='color: red;'>"+
"Could not get data.</span>"
})
This currently gives me two errors:
TypeError: Data should be a "String", "Array of arrays" OR "Array of objects"
TypeError: Cannot read property 'link' of null
I understand what the problem is but I don't know how to return errors so javascript catches it and then displays it in the box like I want it to. Any ideas? Thank you!
At first glance, why don't you just return the error code? It should solve the errors you're getting.
#app.route('/api/download', methods=['POST'])
def download():
data = request.json
#Get data from external API via a post request here
try:
req = urllib.request.Request(url, data, headers)
with urllib.request.urlopen(req) as f:
res = f.read()
print("Success")
data = json.loads(res.decode())
df = pd.json_normalize(data['observationList'])
#Do some pandas magic here
retData = df.to_json(orient="records")
return retData
except Exception as e:
pprint(e)
return 500
This question already has answers here:
Get the data received in a Flask request
(23 answers)
How to get POSTed JSON in Flask?
(13 answers)
How do I post form data with fetch api?
(11 answers)
Closed 3 years ago.
I have a reactjs as a frontend and flask server as a backend. I'm trying to send data from register form (using Formik). When I do a post request I have an error 500.
I notice that when I'm using postman everything is good and flask create new record in postgresql.
frontend is on http://localhost:3000/register,
backend is on http://localhost:5002/adduser
What I should do now ?
function handleSubmit(values, actions) {
const options = {
headers: {
'Content-type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Referrer-Policy': 'origin-when-cross-origin'
},
method: 'POST',
mode: 'no-cors',
body: JSON.stringify(values)
}
fetch('http://localhost:5002/adduser', options)
.then(response => console.log(response))
.catch(error => console.error(error))
}
#app.route('/adduser', methods=['GET', 'POST'])
def register():
if request.method == "POST":
print(request.form['userName'])
print(request.form['email'])
data = {
'name': request.form['userName'],
'surname': request.form['surname'],
'email': request.form['email'],
'user_password': request.form['password'],
'phone_number': request.form['phoneNumber']
}
mydb = Database(host=os.getenv('host'), database=os.getenv('database'), user=os.getenv('user'), password=os.getenv('password'))
mydb.insert_data(data)
return jsonify({'mydata': data})
# name = request.form['name']
# surname = request.form['surname']
# email = request.form['email']
# password = request.form['password']
# phone_number = request.form['phoneNumber']
return "<h1>Hello Flask</h1>"
if __name__ == "__main__":
app.run(debug=True, port=5002)
app.secret_key = os.urandom(24)
You can't access to request.form via json Content-type request.
You need to replace
'Content-type': 'application/json'
By
'Content-Type': 'multipart/form-data'
Your handleSubmit function will be similar to this:
function handleSubmit(values, actions) {
let options = {
headers: {
'Content-Type': 'multipart/form-data'
},
method: 'POST'
};
options.body = new FormData();
for (let key in values) {
options.body.append(key, values[key]);
}
fetch('http://localhost:5002/adduser', options)
.then(response => console.log(response))
.catch(error => console.error(error))
}
}
}
Another possible solution is to keep client code without change and access to your data via request.json instead of request.form.