Handling JSON response from a Django QuerySet via AJAX - javascript

I am passing a Django QuerySet as a JSON response from a Django view.
def loadSelectedTemplate(request):
if request.is_ajax and request.method == "GET":
templateID = request.GET.get("templateID", None)
template = list(operationTemplates.objects.filter(templateID = templateID))
if operationTemplates.objects.filter(templateID = templateID).exists():
ser_template = serializers.serialize('json', template )
return JsonResponse({"valid": True, "template": ser_template}, status=200)
else:
return JsonResponse({"valid": False}, status = 200)
This response is received by the javascript and it can be logged to the console.
// GET AJAX request
$.ajax({
type: 'GET',
url: "{% url 'loadSelectedTemplate' %}",
data: {"templateID": templateID},
success: function (response) {
// if valid template, add to textarea
if (response["valid"]){
var template = response["template"];
console.log(response);
}
Console.log output for the JSON object looks like this;
{
"valid": true,
"template": "[{\"model\": \"opnoteannotator.operationtemplates\",
\"pk\": 14,
\"fields\": {\"templateCategory\": \"Lower Limb\",
\"templateName\": \"Femoral to below knee Bypass using autologous vein\",
\"templatePreopBundle\": \"WHO check list completed.\\r\\n
Antibiotic Chemoprophylaxis: Co-amoxiclav / Teicoplanin / Gentamicin\",
\"templateIndication\": \"CLTI with night pain / rest pain / tissue loss / infection\",
I want to add the objects in "fields" to a text-area on my web page.
How can I achieve this? I have tried different methods but can't seem to get the values accessed in the Javascript.
Thanks in advance.

Maybe you can try:
console.log(response['template']);

I had to convert to the AJAX input from the view.py to a JSON object even though I was passing it as a JsonResponse.
This solution seems to work.
// GET AJAX request
$.ajax({
type: 'GET',
url: "{% url 'loadSelectedTemplate' %}",
data: {"templateID": templateID},
success: function (response) {
// if valid template, add to textarea
if (response["valid"]){
//var template = response["template"];
var tem = response.template;
//convert to JSON object
var res = JSON.parse(tem);
//Empty text area
document.getElementById("opnoteTextArea").value =""
//Display in text area
document.getElementById("opnoteTextArea").value += "Template Name: " + res[0].fields.templateName;
document.getElementById("opnoteTextArea").value += "\n\nPreopBundle:\n" + res[0].fields.templatePreopBundle;

Related

AJAX/FLASK/JS: How to POST existing array into endpoint?

I am trying to POST the songFiles array pushed from the getTableData() function (inside the ajax request) into the /api/fileNames endpoint, which is then sent to a callback postFileNames() that should post the array, but I just can't seem to get it working. Any help would be appreciated, including maybe other ways to do this.
I'm a bit of beginner with using ajax and flask, I have scoured far and wide for a solution, but can't seem to find any to fit my goal, forgive my lack of knowledge.
JavaScript Code
function getTableData() {
$.ajax({
method: "GET",
url: "/api/getSong",
dataType: "json",
success: function(data) {
createMusicTable();
let indexObj = Object.keys(data.song).length;
for (var i = 0; i < indexObj; i++) {
var song = data.song[i]
var id = data.song[i].song_id;
var fileName = data.song[i].song_file + ".mp3";
songFiles.push(fileName);
appendMusic(song, id);
songTitle.id = "s" + i;
console.log("td-ok");
}
postFileNames(songFiles);
}
});
}
function postFileNames(data) {
$.ajax({
method: "POST",
url: "/api/fileNames",
dataType: "json", // data is an array, so not sure what to put here.
data: data, // not sure if correct
success: function(data) {
// should: post the data into the endpoint.
// data is not logged, goes straight to error.
console.log(data)
},
error: function() {
console.log("cry")
}
})
}
FLASK Endpoint Code
#app.route("/api/fileNames", methods=['POST', 'GET'])
def fileNameStorage():
if request.method == 'POST':
data = request.get_data() # not too sure what to do here either.
return data
else:
return "error" # currently goes to 'return error'
#app.route("/api/fileNames", methods=['POST', 'GET'])
def fileNameStorage():
if request.method == 'POST':
data = {
"id": request.json["id"],
"song_name": request.json["song_name"],
"time_duration": request.json["time_duration"]
}
return data, 200
else:
return "error", 400 # currently goes to 'return error'
Would be more prettier if you would :
#app.route("/songs/", methods=['GET', 'POST'])
def songs():
return Songs().get_songs(), 200
In routes.py file
and the other classes and methods in another file
Maybe try jsonify(array) or json.dump(array) if it's a problem to map the array elements.

im not able to send data to view due json serializable

i am getting error set object is not JSON serializable i also used json.dumps but still getting this error ? actually i am trying to save form data to django database with help of ajax but where i am doing mistake
def update_ajax(request):
if request.method == "GET" and request.is_ajax():
nam1 = request.GET.get('nam1')
nam2 = request.GET.get('nam2')
nam3 = request.GET.get('nam3')
n1 = json.loads(nam1)
n2 = json.loads(nam2)
n3 = json.loads(nam3)
print(n1, n2, n3)
return JsonResponse({'success'}, safe=False)
script
function myfun(){
let nam1=document.getElementById('name').value;
let nam2=document.getElementById('email').value;
let nam3=document.getElementById('phone').value;
obj ={
'nam1': JSON.stringify(nam1),
'nam2':JSON.stringify(nam2),
'nam3':JSON.stringify(nam2),
}
$.ajax({
type:"GET",
url: "{% url 'update_ajax' %}",
dataType: "json",
data: obj,
success:function(){
alert('success')
}
});
}

Unable to access json object property and value is displayed undefined in rails view

I've almost viewed similar kind of questions but my problem has not solved yet.
I've following codes.
Controller
def create
#task_list = TaskList.new(task_list_params)
if #task_list.save
respond_to do |format|
format.json { render json: #task_list}
end
else
return
end
end
Ajax Script
$(document).on('click','.add', function(){
count = 0;
user_id = $('#user_id').val();
var name = $('.new-list').val();
var current = $(this);
if(name){
$.ajax({
method: 'POST',
url: action,
dataType: 'JSON',
data: {
task_list: {
name: name,
user_id: user_id
}
}
}).success(function(response){
var data = JSON.stringify(response);
alert(data.id);
$(current).parent().parent().parent().before(
'<div class="col-md-12">'+
''+name+''+
'</div>'
);
$(current).parent().parent().parent().remove();
$('.add-list').show();
});
}else{
alert('please add title');
}
});
I just want to take id of the record just saved to the database through ajax post request. Here, in success function it just alerts undefined and I don't know what's going wrong.
This is sample response.
.success(function(response){
alert(response.id);
Remove JSON.stringify from your success function. Response is already in JSON format you can directly get the value from it.
JSON.stringfy converts javascript object into string.
Explanation
Your response is already in JSON format and you have used dataType: "JSON" in your AJAX call. Which will make it possible to transfer JSON data between server and client.
When your response is already in JSON format you can use its property without parsing it. I.e response.id
If you have not used dataType: "JSON" and you are passing json encoded response from your controller to view file you have to first decode the response to get its values.
var d = $.parseJSON(response);
alert(d.id);

Send a list to django within an ajax GET request

I found a lot of posts here and outside talking about this problem but with POST request.
THIS IS THE PROBLEM: I have a list in my javascript and I need to send that list to django view as argument.
Javascript
$.ajax({
url: "myMethod",
type: "GET",
data: {"par1":par1,"par2":par2,"list":list},
cache: false,
success: function(d){
// DO SOMETHING
}
}
Python
code (views.py)
def myMethod(request):
par1 = request.GET.get('par1')
par1 = request.GET.get('par2')
list = request.GET.get('list') # DON'T WORK
#OR
list = request.GET.getlist('list') # DON'T WORK
#OR
list = request.GET.getlist('list[]') # DON'T WORK
result = DO_SOMETHING(par1,par2,list)
return result
I tried three ways that I found in other posts but none was working.
Could you join the list before posting and the split it in your django view?
Javascript
$.ajax({
url: "myMethod",
type: "GET",
data: {"par1":par1,"par2":par2,"list":list.join("-and-")},
cache: false,
success: function(d){
// DO SOMETHING
}
}
Python code (views.py)
def myMethod(request):
par1 = request.GET.get('par1')
par1 = request.GET.get('par2')
list = request.GET.get('list').split('-and-')
result = DO_SOMETHING(par1,par2,list)
return result

Parse error sending data from JSON to Django

so I'm trying to pass some basic JSON data from javascript to a django view.
Here's my code right now:
var Data = {
Meds: []
};
for(var x = 0; x < pt.meds_arr.length; x++)
{
MedList.Meds.push({"Med": MedData[x]});
};
$.ajax({
url: "django/path",
dataType: "application/json",
data: Data,
success: function(result){
alert(result);
},
error: function(err1, err2) {
alert(err1 + err2);
}
});
Alright, so firebug shows me that this is the data being sent:
Meds[0][Med] Med1
Meds[1][Med] Med2
Which seems right to me.
The django view is:
def query(request):
data = request.GET;
if(data is None):
return HttpResponseBadRequest()
return HttpResponse(data, mimetype='application/json');
The problem is, Django is apparently not handling the data correctly. I'm getting a parse error. In firebug, the response that I get back is:
Meds[1][Med]Meds[0][Med]
Anyone have any idea what may be up? It looks like the data isn't being treated as JSON at some end?
Try this view:
def query(request):
data = request.GET;
if(data is None):
return HttpResponseBadRequest()
#use json.dumps()
return HttpResponse(json.dumps(data), mimetype='application/json');

Categories