Twisted : I cannot get the Ajax "data" parameter - javascript

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 }

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;

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.

Pass Javascript array with Jquery and JSON from client-side to server side in Flask

I am attempting to pass a Javascript Array from the client side to the server side (Flask). My code seems to work for both integers and strings. When I try to send an array with the exact same code, I get None.
Server side code:
#app.route("/route1", methods=['GET', 'POST'])
def route1():
a = request.args.get('post')
result = json.dumps(a)
print(a)
print(result)
Client side:
$SCRIPT_ROOT = {{ request.script_root | tojson | safe }};
var x = ["test", "test2"];
function newFunction() {
console.log(x)
$.getJSON($SCRIPT_ROOT + '/route1', { post: x },
function (data) {
var response = data.result;
console.log(response);
}
)
};
As I said before, this seems to work perfectly when x is simply assigned a string or an integer. When trying to pass through this array, I get None and NULL for my two print statements, respectively. How can I properly pass through the array to the server side?
Yeah, I wasn't able to get this to work using $.getJSON either...
Here's a tested $.ajax solution:
<script>
$SCRIPT_ROOT = {{ request.script_root | tojson | safe }};
var x = ["test", "test2"];
function f1(){
$.ajax({
type: "POST",
url: $SCRIPT_ROOT + "/route1",
contentType: "application/json",
dataType: "JSON",
data: JSON.stringify(x)
});
};
</script>
I trigger this with a button like this:
<button id="testing" name="testing" onclick="f1();">testing</button>
And the Flask code:
#bp.route("/route1", methods=['GET', 'POST'])
def route1():
a = request.get_json()
print(a)
return "hello, world"
you can try below code. it will work. as you are passing array as parameter. as request.args is a MultiDict instance
request.args.getlist(Key)
Or you should try to convert your Array to Json and pass json to Server.
You can use below method to convert json
JSON.stringify()
Server side you can use
data = request.get_json()

ODataController converting json to array

This is in continuation with one of the previous questions
I have a OData Controller with the Action as :
[HttpPost]
[ODataRoute("PostUpdate")]
public async Task<string> PostUpdate(HttpRequestMessage eventsToUpdate)
{
//Do something
}
This is how I am calling the controller through the ajax call:
var eventsToUpdate = [];
for(i=0;i<5;i++)
{
//Build the data
var updatedT = {
"Id" : (Id)?Id:0,
"Desc" : CalculatedDesc
}
eventsToUpdate.push(updatedT);
}
Url = "Api/Odata/PostUpdate"
$.ajax({
url :Url,
type:"POST",
data:eventsToUpdate ,
dataType : 'json',
success : function(result) {
}
});
The problem is even after converting an array to json , the data is not available in the controller's action. This is what I did
var eventsToUpdate = JSON.stringify(eventsToUpdate);
But if I just pass
var updatedT = {
"Id" : (Id)?Id:0,
"Desc" : CalculatedDesc
}
I get the same data in action . What is the solution for this?
What seems to me your [HttpPost] is expecting a key named eventsToUpdate but it doesn't find in the posted request as it is not there because of:
data:eventsToUpdate , // which is eq to = data:[{},{}...],
better to send an object like:
data:{eventsToUpdate:eventsToUpdate} ,
//----^^^^^^^^^^^^^^---------this key will be captured at backend
contentType:'application/json', //<------you would need to add this
and another suggestion is to use traditional:true, if required.
Also, async Task<string> if return type is string then you need to change the dataType of the ajax too or you should return json from the WebMethod.

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