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
Related
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;
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.
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')
}
});
}
I'm executing an ajax call to a external api (this cannot be modified) to upload an store a file into a folder. This request must return a path (ex. "C:\Doctos\File.pdf" but after a console.log is returning something like this:
#document < string xmlns="http://tempuri.org/">"C:\Doctos\File.pdf"
So my question is, what can I do to get only the text that I want without any change in the api (because I'm not able to do it).
Here is the ajax call that I'm using.
PD. This ajax call is using the provided structure for the dev team that developed the api so things like dataType also cannot be modified
var data = new FormData();
var files = $('#fileUpload').get(0).files;
if (files.length > 0) {
data.append("UploadedFile", files[0]);
}
$.ajax({
type: 'POST',
url: 'api/v1/moreurl/UploadFile',
contentType: false,
processData: false,
data: data,
success: function (data) {
var res = data;
//Returns above example
console.log(res);
//Returns something like <p>[object XMLDocument]</p>
$('#MyInput').attr('src', res);
}
});
I would use regular expressions to get the desired string from received data. Put this after success line.
var regex = />\"(.*)\"/;
var matched = regex.exec(data);
var result = matched[1];
console.log(result);
The regex matches the last quoted string in your example.
You can get the data in the xml with jQuery
$.ajax({
type: 'POST',
url: 'api/v1/moreurl/UploadFile',
contentType: false,
processData: false,
data: data,
success: function (data) {
// Get the contents of the xml
var file = $(data).find('string').text();
$('#MyInput').attr('src', file);
}
});
i am passing my arrays like this.but when i am retriving in servlet it is giving nullpointer execption?is this best way to do it ?if no please tell me how can i do much better?
here my .js file
var selected4 = new Array();
var selected3 = new Array();
var selected2 = new Array();
var selected1 = new Array();
i am pushing the values into arrays.my ajax call is like this.
var value3
=domains:selected1,accounts:selected2,categories:selected3,projectType:selected4};
$.ajax({
url: "CategoryReport",
//type: "post",
data: value3,
dataType:'JSON',
cache: false,
success: function(data) {}});
my servlet code is
String[] domains = request.getParameterValues("domains");
for(int i=0;i<domains.length;i++){
System.out.println("domains"+domains[i]);
}
iam getting null values for domains.
It seems like you are using rails?
I come from the .NET world. Being that said, when we want to send an array to a controller we do this,
$.ajax({
url: "CategoryReport",
type: "post",
data: JSON.stringify({ list: value3 }),
dataType:'json',
cache: false,
success: function(data) {}});
});
which willbe passed to the server as a querystring like
list=project1&list=project2&list=project3...
which then you can capture in a String[] list or List<string> list
i hope it helps.