passing data in json format from webpage to flask app - javascript

I want to sent data in json format from a webpage to flask using ajax post method. My tries are as follows :
MY TRY: mytest.html(code snippet)
var jsondat = JSON.stringify(table.getData());
console.log(jsondat);
$.ajax({
type: 'POST',
url: '127.0.0.1:5000/test',
// contentType: 'application/json;charset=UTF-8',
data: {
'data': jsondat
},
success: function(response) {
alert("HELLO")
},
});
Flask App:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/<string:page_name>/')
def render_static(page_name):
return render_template('%s.html' % mytest)
#app.route('/test')
def testfun():
content = request.get_json(silent=True)
print(content)
return 'The test'
if __name__ == '__main__':
app.run()

Related

js to flask and back to js in a single page app

For my single page web app, I need to:
Send a json from .js to flask (DONE)
Run the input through a python function - getString() and get a str output (DONE)
Send the str output back to the .js file (PROBLEM)
Here is the flask app:
#app.route('/',methods =['GET','POST'])
def index():
req = json.dumps(request.get_json())
if request.method == 'POST':
result = getString(req) #Function outputs a string
return jsonify(result)
else:
print('Not Received')
return render_template('index.html')
if __name__ == '__main__':
app.run()
The problem is that the jsonify(result) is not being sent probably due to the request.method == 'POST' switching to else when jsonify is called. Is there any way to fix my code to send the str output to the .js?
Here is the .js:
//To send info to flask
document.querySelector('#generate').addEventListener('click',function() {
var json_inputs = JSON.stringify(inputs);
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/",
traditional: "true",
data: json_inputs,
dataType: "json"
});
})
//To receive from Flask
$.ajax({
url: "/",
type: 'GET',
success: function(data) {
console.log(data);
}
});
I think you've misunderstood what GET and POST are, GET is a request that only fetches something from the back end without a message body but a POST can send a body and recieve something.
try this instead:
document.querySelector('#generate').addEventListener('click',function() {
var json_inputs = JSON.stringify(inputs);
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/",
traditional: "true",
data: json_inputs,
dataType: "json",
success: function(data) {
console.log(data);
}
});
})

JSON object sent from Javascript to Django Views is empty

I'm trying to send some data from Javascript to Django through ajax.
Here is my JS code:
var json_name = {'name': 123}
$.ajax({
method: 'POST',
url: 'my url',
contentType: "application/json",
headers: {
'Content-Type':'application/json',
'X-CSRFToken': "{{ csrf_token }}"
},
data: JSON.stringify(json_name),
success: function (data) {
//this gets called when server returns an OK response
alert("it worked!");
},
error: function (data) {
alert("it didnt work");
}
});
Here is my Views.py:
def myview(request):
if request.is_ajax():
request_data = request.body
# data = json.loads(request.body)
print(request_data)
# print(data)
return render(request, 'candidate/view.html')
else:
return render(request, 'candidate/view.html')
I get the output as b''
When I try to include these lines:
data = json.loads(request.body)
print(data)
I get this error:
TypeError: the JSON object must be str, not 'bytes'
I took some reference from here
Can someone help me with this? If you need any additional information to solve this, I'll be happy to share.
After losing half the hair on my head, I solved it in the following way:
views.py:
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def myview(request):
if request.is_ajax():
if request.method == 'POST':
data = request.POST.get('senddata')
print(data)
return render(request, 'candidate/view.html')
else:
return render(request, 'candidate/view.html')
my JS code:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
$.ajax({
type: 'POST',
url: 'my url',
// contentType: "application/json",
// headers: {
// 'Content-Type':'application/json',
// 'X-CSRFToken': "{{ csrf_token }}"
// },
dataType: "json",
data: {
senddata: JSON.stringify(json_name),
},
// data: json_name,
success: function (data) {
//this gets called when server returns an OK response
alert("it worked!");
},
error: function (data) {
alert("it didnt work");
}
});
When I run it, it shows it didnt work but I can see the output in my terminal i.e The data was passed.
I tried including the csrf token in the ajax request but it failed. Therefore I used csrf_exempt in my views.
This might be a dirty way of doing things, but it works for now. If anyone has a neat and better answer please post it here!!
I've written a basic testcase on Django 1.11 with Python 3.6 and Python 2.7.
I have been using the following template file to test:
<button>Send data</button>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$('button').on('click', function(event) {
var data = { name: 123 };
$.ajax({
method: 'POST',
url: '',
contentType: 'application/json',
headers: {
'X-CSRFToken': '{{ csrf_token }}',
},
data: JSON.stringify(data),
success: function() {
console.log('Success!');
},
error: function() {
console.log('Error...');
},
});
});
</script>
And the following route, which delivers the template file and prints any AJAX data:
from django.http import response
from django.shortcuts import render
import json
def index(request):
if request.is_ajax():
request_body = request.body
data = json.loads(request_body)
print(data)
return render(request, 'stackoverflowhelp/index.html')
I've not been able to reproduce the issue.
However, having done more research I found that the json.loads method in Python 3.6 supports bytes objects, while the documentation for Python 2.7 json.loads suggests it only supports string types. While the error you've posted reflects this, I've attempted to make this generate the same error as you're seeing but have had no success.
As you can see, I've not had to whitelist the method from CSRF protection. Based purely on the error you've provided, calling decode on request.body may work:
def index(request):
if request.is_ajax():
request_body = request.body.decode("utf-8")
data = json.loads(request_body)
print(data)
return render(request, 'stackoverflowhelp/index.html')

Datatable from server json object

I submitted a form data to a backend Flask application as ajax post request. Backend process uses data to query database then returns json object back to Ajax. How to construct datatable from this json object?
My Ajax post request:
$(document).ready(function() {
$("#submit").click(function(event) {
$.ajax({
type: 'POST',
url: '/process',
data: $('#myform').serialize(),
success: function(response) {
//response looks like this:
//[{"country": "USA", "code": "1007-01" },{"country": "UK", "code": "1100-04" }]
}
});
event.preventDefault();
});
});
My flask application
#app.route('/process', methods=["POST"])
def process():
if request.method == 'POST':
country = request.form['id'].encode("utf-8")
#query database and store result in dict
result = query_database(country)
return jsonify(result)
Initialize your datatable with your ajax call as datasource
let datatable = $('#my-table').DataTable({
ajax: {
url: '/process',
method: 'POST',
data: {
$('#myform').serialize()
}
}
});
now you just need to format your response like this
{
data:[/*your Data*/]
}

Error when using JSON to send Javascript object to Python Flask

I am using ajax to POST a JSON string to Python Flask but get the following error:
Error
This is my JavaScript:
$.ajax({
type: 'POST',
url: window.location.href,
data: JSON.stringify(questionObj0),
dataType: 'json',
contentType: 'application/json; charset=utf-8'
}).done(function(msg) {
console.log(msg);
});
And this is my Python:
#app.route('/test', methods=['GET', 'POST'])
def test():
question = request.get_json()
question1 = json.loads(question)
print (question)
return render_template('test.html')
Using print(question) yields the following output (same output when tested in JavaScript using browsers console):
{'questionNumber': 1, 'question': 'Convert 10110001 to decimal', 'answer': 177, 'userAnswer': 'blank'}
From what I understand, the output should be a string and therefore padded with quotation marks.
Has anyone come across anything similar/know how to fix the issue?
Flask's request.get_json() returns a dict object from the JSON data supplied in the request, so you don't need to call json.loads on it again.
app.py
#app.route('/', methods=['GET'])
def index():
return render_template('index.html')
#app.route('/test', methods=['POST'])
def test():
question = request.get_json()
print(question['question'])
return ''
templates/index.html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var questionObj0 = {'questionNumber': 1, 'question': 'Convert 10110001 to decimal', 'answer': 177, 'userAnswer': 'blank'};
console.log(JSON.stringify(questionObj0));
$.ajax({
type: 'POST',
url: '{{ url_for('test') }}',
data: JSON.stringify(questionObj0),
dataType: 'json',
contentType: 'application/json; charset=utf-8'
}).done(function(msg) {
console.log(msg);
});
</script>

Send variable from JavaScript into Flask

I'm a complete beginner here and facing a problem in passing javascript variable into flask. Please note that my question is completely different from previous question that has been asked.
This is my code:
JavaScript
var dd = {'mvar': 1};
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/",
data: JSON.stringify(dd),
success: function (data) {
alert("DONE!")
},
dataType: "json"
});
Flask(edited)
#app.route('/', methods=['GET', 'POST'])
def new():
form = InputForm(request.form)
v = request.get_json().get('mvar')
print(v)
return render_template('new.html',form=form,v=v)
However, when the output that I get when print out the result is "None" while I expected it to be "1"
Really hope that experts can help me, thank you!
The Request.get_json() method is what you are looking for in your Flask code.
data = request.get_json()
edit here is the exact pattern i use which works:
javascript:
$.ajax({
type: "POST",
url: "{{ url_for("get_post_json") }}",
contentType: "application/json",
data: JSON.stringify({hello: "world"}),
dataType: "json",
success: function(response) {
console.log(response);
},
error: function(err) {
console.log(err);
}
});
python:
#app.route('/_get_post_json/', methods=['POST'])
def get_post_json():
data = request.get_json()
return jsonify(status="success", data=data)
Instead of using
v = request.form.get('mvar', type=int)
Use this
v = request.get_json().get('mvar')
Once you print v then you should get it.

Categories

Resources