I am using python3.6 and Django 2.0.3 on Ubuntu 17.10. I'm a bit new to Django and trying to understand it. I have a table with some input fields in the html page where the users will enter data. My AJAX code below gets the data from the table rows and passes it to django view. CSRF is handled as per the django documentation as I have no form in my html.
Here is my AJAX code (using jQuery)
$(document).ready(function() {
var table = $('#example').DataTable();
$('button').click( function() {
var TableData = new Array();
$('#example tr').each(function(row, tr){
TableData[row]={
"id" : $(tr).find('td:eq(0)').text()
, "student_name" :$(tr).find('td:eq(1)').text()
, "marks" : $(tr).find('td:eq(2) input', this).val()
, "is_present" : $(tr).find('td:eq(3) select', this).val()
}
});
TableData.shift(); // first row will be empty - so remove
TableData = JSON.stringify(TableData);
alert(TableData);
$.ajax({
type: "POST",
url: "{% url 'result:ajax_update_result' %}",
dataType: 'json',
data: TableData,
success: function(msg){
alert(msg);
}
});
return false;
} );
});
Here is the result of the alert call in the above AJAX. The same data is passed to the djago view code which handles this AJAX call.
[{"id":"1","student_name":"Test Student","marks":"0.00","is_present":"1"},{"id":"2","student_name":"Test Student3","marks":"0.00","is_present":"1"}]
Below is my django view for the above AJAX call.
import json
def save_result(request):
table_data = json.dumps(request.GET.get('TableData'))
print(table_data)
return render(request, 'data/dummy.html', {'msg': 'Data Saved.'})
The django console prints null for the above print(table_data)
Please note: I used json.loads in the django view code and got a type error.
I am expecting the data from the AJAX call to be passed to the django function and the data printed in console as dictionary.
You should first stringify your JSON data:
$(document).ready(function() {
var table = $('#example').DataTable();
$('button').click( function() {
var TableData = new Array();
$('#example tr').each(function(row, tr){
TableData[row]={
"id" : $(tr).find('td:eq(0)').text()
, "student_name" :$(tr).find('td:eq(1)').text()
, "marks" : $(tr).find('td:eq(2) input', this).val()
, "is_present" : $(tr).find('td:eq(3) select', this).val()
}
});
TableData.shift(); // first row will be empty - so remove
alert(TableData);
$.ajax({
type: "POST",
url: "{% url 'result:ajax_update_result' %}",
dataType: 'json',
data: JSON.stringify({'TableData': TableData}),
success: function(msg){
alert(msg);
}
});
return false;
} );
});
And retrieve it from request.POST:
import json
def save_result(request):
table_data = json.loads(request.POST.get('TableData'))
print(table_data)
return render(request, 'data/dummy.html', {'msg': 'Data Saved.'})
Note I'm using json.loads since your data is now stringified.
EDIT: I just realized you were actually stringifying your TableData...however, you were trying to pull from a non-existent key TableData from request.GET. I believe my updated answer should work for you.
Related
I am trying to create An ajax request in the Django template .. it fails and returns an empty error so am not even able to debug it.
Here is what I tried to do :
HTML template
.....
kml_layer.addListener('click', (kmlEvent) => {
setMapOnAll(null);
var clickedPoint = kmlEvent.latLng;
newPoint.postMessage(clickedPoint.lat() + "," + clickedPoint.lng());
$.ajax({
type: "POST",
url: "https://www.{{domain}}{% url 'get_km_from_source' %}",
data: {
csrfmiddlewaretoken: '{% csrf_token %}',
layer_id: "{{ single_layer.id }}",
the_element_string_id: kmlEvent.featureData.id,
clicked_lat: kmlEvent.latLng.lat,
clicked_lng: kmlEvent.latLng.lng
}, /* Passing the text data */
success: function (response) {
alert("Thankyou for reaching us out " + response);
},
error: function (jqXHR, textStatus, errorThrown) {
// alert the error if any error occured
console.log(textStatus, errorThrown);
}
});
});
.....
And here is the URL that is being called.
path('get_km_from_source/', get_km_from_source, name='get_km_from_source'),
Using print debugging in the python function that is being called.. it never reaches this point. but it always fails before starting the request .. and it returns an empty based on the lin console.log(textStatus, errorThrown); .. here is how the error looks like :
console output: "error "
I am not able to retrieve data field of AJAX in python flask.
Its shows type error when I try to retrieve data. type and forwho are of array type. When I alert them in AJAX it works.
Here is my code,
// Ajax
$.ajax({
url: '/products',
data: JSON.stringify({'type':type,'forwho': forwho}),
contentType: "application/json; charset=utf-8",
type: 'POST',
success: function(response){
/*alert("success");*/
$("#content").html(response);
},
error: function(error){
/*alert("error");*/
console.log(error);
}
});
# app.py
#app.route('/products', methods =['POST', 'GET'])
def all_products():
if request.method == 'POST':
print("inside all products post")
type = json.loads(request.form.get('type'))
forwho = json.loads(request.form.getlist('forwho'))
print(type)
print(forwho)
when I print print(request.args.get('typearr')) in all_products() it returns None
type =request.json['type']
forwho = request.json['forwho']
Flask automatically parses JSON when having application/JSON in your request.
This solution finally worked for me.
ajax:
data: JSON.stringify({'typearr':type,'forwho':forwho})
``````````````````
app.py:
#import ast
``````````````
data = request.get_data()
data = ast.literal_eval(data.decode("UTF-8"))
typearr = data['typearr']
forwho = data['forwho']
I was trying to get some information from API using ajax. I was able to post data but I was unable to get all the data from the server. I am new in the Django environment, though i have tried some references. I was wanted to get the data from the server using the API that I provide and show those data by using ajax get call.
References that I have followed:
1.Django Ajax Jquery Call
2.https://simpleisbetterthancomplex.com/tutorial/2016/11/15/how-to-implement-a-crud-using-ajax-and-json.html
3.https://www.sourcecodester.com/tutorials/python/11762/python-django-simple-crud-ajax.html
My code for get call:
$.ajax({
type: "GET",
url: "/save_composition",
dataType: "json",
success: function(data) {
alert(data)
},
error: function(xhr, textStatus) {
alert("error..");
}});
Url section :
path('restore_composition/', views.restore_composition, name='restore_composition')
Views.py:
def restore_composition(request):
data = SaveComposition.objects.all()
return render(request, 'index.html', context={'data': data})
This is how ajax calls works in Django framework.
def ajax_method():
return HttpResponse(200)
url to the ajax call
path('save_composition', views.ajax_method, name='ajax_method')
You need to set the `url-path' without forward-slash
Ajax call
$.ajax({
type: "GET",
url: "save_composition",
dataType: "json",
success: function(data) {
alert(data)
},
error: function(xhr, textStatus) {
alert("error..");
}});
I'm working on a flask web application in which the client posts data to the server in the form of:
{
"sess_id" : 1 ,
"annotations" :
[ {"tag_start" : "TIME","tag_end" : "TIME","tag" : "YOUR_TAG"}, {"tag_start" : "TIME","tag_end" : "TIME","tag" : "YOUR_TAG"}, {"tag_start" : "TIME","tag_end" : "TIME","tag" : "YOUR_TAG"}]
}
Here is the full Ajax post...
$.ajax({
url: 'http://127.0.0.1:5000/api/saveannotation',
type: 'POST',
headers: {'Content-Type' : 'application/json'},
data: {'sess_id' : $('#sessionid_area').val(),
'annotations': JSON.parse(annotations)},
success: function(data) { alert(data.status); }
});
so I can even see this on the api side, which is defined as such:
#sessionapis.route('/saveannotation', methods=['GET', 'POST'])
#login_required
def save_annotation():
rData = request.data
if request.method == 'GET':
return jsonify({'status' : 'success GET'})
else:
return jsonify({'status' : 'success'})
The issue is that data is a "byte" type, not a dict. I also can't call request.json or request.get_json(silent=True), it returns "400 bad request".
Here is a sample of what is in request.data:
b'sess_id=1&annotations%5B0%5D%5Btag_start%5D=2...
it appears to be url encoded for some reason. Values is also empty. If I choose to do something wild, like leave out the content-type = json; I can get a dict-like thing, but I have to access it very oddly. I don't get individual objects, but rather just flat access to all properties.
Any thoughts on how to just get the json parsed into a reasonable object?
Thanks for any hints!
Just passing a content-type header of JSON doesn't actually make the data itself into JSON. You either need to do that yourself, or tell jQuery to do so.
$.ajax({
url: 'http://127.0.0.1:5000/api/saveannotation',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({'sess_id' : $('#sessionid_area').val(),
'annotations': JSON.parse(annotations)}),
success: function(data) { alert(data.status); }
});
Now your data will be in JSON format and you can get it as a Python dict with request.get_json().
I have various decorators preveting users to access different urls if they don't have filled data. I want to know what is the best way to show a modal with the data that user needs to be filled using decorators.
I've managed to find a solution myself: I' changed all the links to
<a href="#" onClick="linkWrapper(<url_to>,'{{ request.path }}')">
Here is the linkWrapper function
function linkWrapper(url_to,url_from)
{
var content = '';
$.ajax({ type: "GET",
url: url_to,
async: false,
cache: false,
success : function(data){
if (typeof data == 'object'){
response = JSON.parse(data);
if (response['error'] != undefined)
if(typeof response['error'] == 'object')
ModalToggle(response['error']['url'],response['error']['url'],'#form',response['error']['title']);
else
ToggleSimpleTextModal(response['error']['text'],'Ошибка доступа');
else
window.location = url_from;
}
else
window.location = url_to;
}
});
}
And all the decorator has to return is a json object which contains form url.