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

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.

Related

Handling JSON response from a Django QuerySet via AJAX

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;

Twisted : I cannot get the Ajax "data" parameter

An ajax "POST" is triggered witht these paramaters:
function test22(portnb){
console.log(portnb)
$.ajax({url: "action",
dataType : 'html',
type: "POST",
data: portnb,
success: function( strData2 ){;
console.log(strData2);
$("#content3").html(strData2);
}
});
};
It is handled by a twisted python script:( see the interresting part below)
class Test3Handler(resource.Resource):
isLeaf = True
def __init__(self):
resource.Resource.__init__(self)
def render_POST(self, request):
argo = request.content.getvalue()
print( argo )
retp = "<ul><li>"
retp += argo
retp += "</ul>"
print (retp)
return retp
if __name__ == "__main__":
import sys
from twisted.internet import reactor
testHandler = TestHandler()
test2Handler = Test2Handler()
test3Handler = Test3Handler()
root = static.File('/home/pi/web4')
root.putChild('test', testHandler)
root.putChild('test2', test2Handler)
root.putChild('action', test3Handler)
reactor.listenTCP(8082, server.Site(root))
reactor.run()
The issue is that I cannot get the "data" parameter sent by Ajax ( data : portnb). the variable "argo" is empty.
I am new to Python/Ajax.
Can you help me to fix this issue?
It will be very helpful to develop something more complex later.
Thanks
Gilles
portnb = 23. When Ajax "data : {portnb}", the python script receives "portnb = 23". I would only need to get 23, not portnb = 23. Is there an easy way to do this? Thanks, Gilles
You should set the dataType to json and in the data field send an object like { params: portnb }

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

Using cookies to check if anonymous user voted

I'm working on a webapp that uses Flask as the backend server. There are posts that I'm storing in an SQLAlchemy database, and I want the users to be able to upvote/downvote them without having to log in. I wrote a JavaScript function for upvoting/downvoting that increments the current vote count and then updates the count in the database using Ajax. I want to make sure that the same user doesn't vote on the same post twice; it doesn't have to be robust. I read that cookies could be used for that purpose, or a combination of cookies and IP. I'm having a hard time understanding how to get started: do I assign a cookie to a user in JS or in Flask? How do I check whether the user already voted? I'd appreaciate if someone could show me a simple example or direct me to a good resource. Thanks a lot.
Here's my Javascript part for upvoting:
$(document).ready(function() {
$('#{{ upbtnID }}').click(
function() {
var postID = "{{ answer.id }}";
var data = {
'id': "{{ answer.id }}"
};
var score = document.getElementById('{{ scoreID }}');
var scoreText = score.textContent;
var scoreToInt = parseInt(scoreText, 10);
var newScore = ++scoreToInt;
var scoreToStr = newScore.toString();
$(this).css('border-bottom-color', '#26EDEB');
score.textContent = scoreToStr;
$.ajax({
url: "/upvote",
data: JSON.stringify(data, null, '\t'),
contentType: 'application/json;charset=UTF-8',
type: 'POST',
success: function(response) {;
},
error: function(error) {
alert("Awww");
}
});
});
And the corresponding function in Flask:
# upvote a post
#app.route('/upvote', methods=["GET", "POST"])
def upvote():
if request.method =="POST":
thePostID = int(request.json["id"])
thePost = Answer.query.get(thePostID)
thePost.score += 1
db.session.commit()
data = thePost.score
return ('', 204)
Quoting from Flask snippets:
#app.route('/set_cookie')
def cookie_insertion():
redirect_to_index = redirect('/index')
response = current_app.make_response(redirect_to_index )
response.set_cookie('cookie_name',value='values')
return response
Link: http://flask.pocoo.org/snippets/30/

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