I want to send data to a flask app without using ajax or jquery(only using vanilla js). I found that fetch offers to do the same however, I'm not able to make it work.
My Code
html code
<a href="#" id="link{{i}}" onclick="getdata(this.id)">
<script>
function getdata(id){
let numberId = id.slice(-1);
var data = new FormData();
data.append( {{data.links[numberId]}} );
fetch("/recipes",
{
method: "POST",
body: data
})
.then(function(res){ return res.json(); })
.then(function(data){ alert( JSON.stringify( data ) ) })
}
</script>
My python code
elif request.method == "POST":
clickedLink = flask.request.args.get("body")
print(clickedLink)
Update:
Some errors I'm receiving.
Receiving the following error
Related
I have an array of dictionaries in javascript that I want to send as payload to a POST request to flask.
However, the array always gets sent empty.
Javascript:
{% for department in departments %}
var department_id = "{{ department.id }}"
var cardgroup = $("#cardgroups_{{ department.id }}").val();
var doorgroup = $("#doorgroups_{{ department.id }}").val();
data.push({
department_id: department_id,
cardgroup_id: cardgroup,
doorgroup_id: doorgroup
});
{% endfor %}
$.post("data/save-office/"+office, data={data: data}, function (data) {
if (data['error']) {
alert(data['error']);
}
else
if (data['success']) {
load_table();
}
});
python:
#app.post('/data/save-office/<office>')
def save_office(office):
departments = request.args.getlist('data[]'). # departments = []
I tried to change departments to request.args.getlist('data') but it returned the same thing.
I also tried to use AJAX instead but it was basically the same thing.
Based on only provide an answer to your original question, you can pass an array to flask as the body of a POST request, Flask automatically handles JSON to dict conversion as-is.
Consider this code block as an example of how to send that data:
var my_json_array = [{
"key": "val"
}, {
"key": "val"
}]
async function postData(url = '', data = {}) {
const response = await fetch(url, {
method: 'POST', .
headers: {
'Content-Type': 'application/json'
},
body: data
});
return response.json();
}
postData('http://localhost:5000/test', my_json_array)
.then(data => {
console.log(data);
});
Note: I want to give credit to MDN for the fetch API sample I used on this post, visit https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch to know more about this new JavaScript API feature
I need to get some data from my template and send it back to my Django function using ajax, create a docx file and download it
Django Function
def download_docx_file(request):
if request.method == 'GET':
language = request.GET['lang']
data = request.GET['data']
converter = {'data': 'This is the real data'}
document = Document()
document.add_heading(f'{language} -- {converter[data]}', 0)
response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
response['Content-Disposition'] = 'attachment; filename=download.docx'
document.save(response)
return response
return HttpResponse("hello")
AJAX
$("#dwnBtn").click(function(){
$.ajax({
url : "docx/",
type:"GET",
data : { lang : 'lang', data:'data' },
success : function(data){
console.log(data)
}
})
});
I am getting sth like the below response from AJAX response:
Response console.log(data)
�ܝBp��݂�;|C�ھ�w������=O���]]�%�N�����#+�reup����������Y������̉�J����3)� O��C����F�M�P�&�����rA�#��7T.��z(%h��x�x0�0Z�-i��%q�e�M�����i�"�c��-/��j��齔/ļL瞄�0� �� >�o��[��6 멆�n��s�$�
�#>˘ '��wT�� ���3�36DK�+�̓�t6 ��r��sA:���x�<>n������'U��RLqA+���ݺ�BM��:4ĞP�}���:�}ߣP����?F)�9-�W0���2�{x��#2v8N.$V�>X=/�+�c}���ּ�\y���*�J\��
���90�T�L� 3p���*Sfj(���PWWz��O�s�9]&����iO|�9�;�5��ʘdW�cl% �%;����u���%[�5������Q]$��[L>���yXg�9��2+&,iFs�Q�����u�.�E(�>W��+��M ؟E������i|���k�k�c蟴CcG�j��4s|x �F1�}��Y��,29�0M=-O����m\L��y��^On^���\���u��a���F9:zc�Sy�-�g��fu�n�C�T:{ ��4&/ ��LM9�98� �&Pnc�!��m�r�~��)74�04��0�0������M�~"��.ikjG��M�
how can I save this binary data as a .docx file?
Thank you in advance
I am trying to submit localstorage data via a POST request using the below jquery ajax method. How should I write my view so I can Parse my JSON object and get a hold of "product_id" to execute the below command in my Django view. Please see a copy of my view below.
Trying since one week, but I failed to fix the issue
Is there any better way of achieving this ?
My Ajax:
$(document).ready(function() {
var compare = localStorage.getItem("comparisionItems");
var compareObj = JSON.parse(compare);
var data_url = window.location.href;
console.log(compare)
console.log(compareObj)
$.ajax({
url: data_url,
type: "POST",
data: {'compare_id': compareObj },
headers: { "X-CSRFToken": $.cookie("csrftoken") },
success: function (result) {
console.log("Success")
},
});
});
and My Views:
def compare(request):
is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
if is_ajax and request.method == "POST":
compare_id= request.POST.getlist('compare_id[itemIds]')
product = get_object_or_404(Products, id=compare_id)
context={ 'product':product}
return render (request, './compare.html', context)
Actually my localStorage is on following format:
("comparisionItems"({ images: products, itemIds: itemIds }));
Can you please help me how can I pass itemIds to views and return item from views for the itemsIds?
Console log for console.log(compareObj)
https://imgur.com/MxdZrgy
since .is_ajax() is deprecated you cant use that, but you can check if the request is an XMLHttpRequest like below.
from django.shortcuts import get_object_or_404
def compare(request):
is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
if is_ajax and request.method == "POST":
compare_id = request.POST.get('compare_id')
product = get_object_or_404(Products, product_id=id)
context={ 'product':product,}
return render (request, './ecommerce/compare.html', context)
note; the get_object_or_404 is just a shortcut for:
try:
product = Products.objects.get(product_id=id)
except:
raise Http404
I would like to send json formatted data from my html page to a url on the click of a button, but currently the data is not getting updated to the url. I've included here a small subset of the data i'm trying to post. The GET method works fine for posting initial output to the url. The result of the ajax request is the alerted error output. How can I use POST to successfully update the output to the url?
The html:
<button type="submit" class="btn-sm btn-success btn-space" id ="commitButton" name="commitButton" value="enter">Commit</button>
Javascript:
<script>
document.getElementById('commitButton').onclick = function() {
$.ajax({
url: "/processjson",
type:'POST',
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
"dataType": "json",
"data": {"schema": {"fields":[{"name":"index","type":"integer"},{"name":"OB_TIME","type":"datetime"},{"name":"LATITUDE","type":"number"},{"name":"LONGITUDE","type":"number"}]}, "data": [{"index":0,"OB_TIME":"2015-09-03T00:00:00.000Z","LATITUDE":21.9,"LONGITUDE":-152.0}]},
"contentType": "application/json",
success: function(result) {
alert('ok');
},
error: function(result) {
alert('error');
}
})
};
</script>
Flask:
#app.route('/processjson', methods=['GET','POST'])
#login_required
def processjson():
if request.method == 'GET':
return jsonify({'result':'Test'})
# getting the table data when the commit button is pressed
if request.method == 'POST':
# gets jsonified data and convert it to a python data structure (dictionaries)
data = request.get_json()
fields = data['schema']['fields']
tableData = data['schema']['data']
return jsonify({'result':'Success!','tableData' : tableData})
Place the json data inside the request body.
You can access the request body with request.form.get('data') to get a json string. This can be load to a dict using json.load(json_str).
request.get_json() parse form data as json, but this would work if you are submitting as form data. Looking at the JS snippet, it looks like you are not submitting it as form data (you are making an ajax call), so your data will be available in the property request.json
you can use like this : request.json
I need to send json data using a POST request from Angularjs to my Django view.
I need to get data from database using this json as json format.
I tried some examples using from net resources:
JS Code:
$http({
method: 'POST',
url: '/mycard/list',
data: $.param({test: json})
});
Python Code(Django View):
def product_list(request):
if len(request.META['QUERY_STRING']) > 0:
data = request.body
data = json.loads(data)
print data
else:
f = open('./mytest.txt','r')
data = f.read()
return HttpResponse(data, mimetype='application/json')
But it returns 403 error and sometimes it returns 500 error(INTERNAL SERVER ERROR)
Service Code
var promise = $http({
method: 'post',
url: '/mycard/list',
data:data,
contentType:'application/json; charset=UTF-8',
});
return promise;
Python rest api
#csrf_exempt
#api_view(['GET','POST'])
def product_list(request):
if request.method == 'POST':
try:
stream = StringIO(request.body)
data = JSONParser().parse(stream)
except ValueError:
return Response(json.dumps(ValueError, default=json_util.default))
return Response(json.dumps(data, default=json_util.default))
else:
return Response("failure")
your json data should be formatted by JSON.stringify() like this:
$http({
method: 'POST',
url: '/mycard/list',
data: JSON.stringify({test: json})
});
403 Forbidden maybe because of an invalid CSRF token
500 : You might be not posting the data in the format that the backend is expecting. Can you please inspect and see what is the error response it is giving.