django get data from api with ajax - python

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..");
}});

Related

Issue with sending data to python flask from AJAX

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']

passing JSON data to django using AJAX

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.

web2py - getting posted json data through jquery

I'm new to web2py, trying to alter an existing application.
I have a JSON object in my JS, which I want to send to the server.
My JS is:
post_data = {ios: [{k:"v"},
{k: "v"},
{k: "v"}]};
$.post("/url", post_data, function(data) {}, "json"); // used with 'json' and without, same results
I want to access this data in my controller. so there, I tried to use request.vars.ios and request.post_vars.ios, getting a None ...
What am I doing wrong?
(note: the data is transmitted, and if i try to dump the request.vars, I get something like
<Storage {'ios[1][ranges_colors]': '', 'ios[0] .... etc which contains the data)
Try this, on the client:
$.ajax({
type: 'POST',
url: '/url.json',
contentType: "application/json; charset=utf-8",
data: post_data,
dataType: 'json',
success: function(data) { alert('Data sent'); }
});
Then on the server:
data = gluon.contrib.simplejson.loads(request.body.read())

Ajax request in flask not working

I am working on a flask app and I am sending this ajax request to '/repl' endpoint
$.ajax({
type: "GET",
url : "/repl?code=",
data: "print \"hello\"",
contentType: 'application/json;charset=UTF-8',
success: function(result){
alert(result.output);
}
});
and code of my controller i.e. view.py is
#app.route('/repl', methods=['GET'])
#app.route('/repl/', methods=['GET'])
def execute():
code = request.args.get("code", None)
print code
# execute python code in sandbox
out, err = exec_sandbox(str(code))
return jsonify(success=1, output=out, error=err)
but it is not working. Code variable always receives None value. Please help
after running app, this request builds up
127.0.0.1 - - [28/Mar/2014 03:59:59] "GET /repl/?code=&print%20%22hello%22 HTTP/1.1" 200
change ajax code to :
$.ajax({
type: "GET",
url : "/repl",
data: {url : "print \"hello\""},
contentType: 'application/json;charset=UTF-8',
success: function(result){
alert(result.output);
}
});

How to post data structure like json to flask?

I have a data structure like this:
I'm try to send it to server by $.ajax:
$.ajax({
type: 'POST',
data: post_obj, //this is my json data
dataType: 'json',
url: '',
success: function(e){
console.log(e);
}
});
and I want get it in server by flask: title = request.form['title'] working fine!
But how do I get content ?
request.form.getlist('content') doesn't work.
This is the post data in firebug:
Thanks a lot :D
You are sending your data encoded as query string instead of JSON. Flask is capable of processing JSON encoded data, so it makes more sense to send it like that. Here's what you need to do on the client side:
$.ajax({
type: 'POST',
// Provide correct Content-Type, so that Flask will know how to process it.
contentType: 'application/json',
// Encode your data as JSON.
data: JSON.stringify(post_obj),
// This is the type of data you're expecting back from the server.
dataType: 'json',
url: '/some/url',
success: function (e) {
console.log(e);
}
});
On the server side data is accessed via request.json (already decoded):
content = request.json['content']
If you inspect the POST being submitted by jQuery, you will most likely see that content is actually being passed as content[]. To access it from the Flask's request object, you would then need to use request.form.getlist('content[]').
If you would prefer to have it passed through as content, you can add traditional: true to your $.ajax() call.
More details about this can be found in the 'data' and 'traditional' sections of http://api.jquery.com/jQuery.ajax/.

Categories