im not able to send data to view due json serializable - javascript

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')
}
});
}

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.

Sending Json Array in POST request for JavaScript

I am having trouble in sending a JSON array in an AJAX call. Following is my Code
var company_name = $('input#company_name').val();
var company_localname = $('input#company_localname').val();
var companytype = $('#companytype').val();
if (companytype == 'retailer') {
var bank_name = $('input#bank_name').val();
var account_title = $('input#account_title').val();
var business_nature = $('input#business_nature').val();
var gross_sales = $('input#gross_sales').val();
}
After getting all the values I am storing the data in Json like the following
var jsonArray = [];
jsonArray["company_name"] = company_name;
jsonArray["company_localname "] = company_localname;
if (companytype == 'retailer') {
jsonArray["bank_name"] = bank_name;
jsonArray["account_title"] = account_title;
jsonArray["business_nature"] = business_nature;
jsonArray["gross_sales"] = gross_sales;
}
Now for sending the jsonArray in Ajax call
$.ajax({
url : url,
type : "POST",
dataType : 'json',
contentType : 'application/json; charset=UTF-8',
data : JSON.stringify(jsonArray),
success : function(response) {
//Some Code here
}
});
Please help me sending data. Or tell me if I am making any mistake here. Thank you
In JavaScript / JSON arrays are 0 based indexed data structures. What you are using here is more like a Map:
var jsonArray = [];
jsonArray["company_name"]=company_name ;
In JavaScript you cannot use arrays like this (well you can, but it is probably not what you want). For a data structure like a map that maps strings to objects rather then an index to objects, just use an object.
Or in short: Use var jsonArray = {}; rather than var jsonArray = []; The {} will create an object that you can assign properties to like you did. And JSON.stringify will correctly translate this into a JSON string like this:
{ "property": value, "otherProperty", otherValue }
Do something like this.
$.ajax({
url: url,
type: "POST",
dataType: 'json',
contentType: 'application/json; charset=UTF-8',
data: JSON.parse(JSON.stringify(jsonArray)),
success: function(response) {
//Some Code here
}
});
The JSON.parse() method parses a string as JSON, optionally transforming the value produced by parsing. Read more about JSON.parse() method
The JSON.stringify() method converts a JavaScript value to a JSON string. Read more about JSON.stringify() method
Here simply you can send an array and Parse it in server side.
$.ajax({
url : url,
type : "POST",
dataType : 'json',
data : jsonArray,
success : function(response) {
//Some Code here
}
});

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

Why doesnt this javascript code work?

I have a javascript function
function TxEncrypt(event)
{ //perform encryption of token data, then submit the form like normal
//obtain public key and initial JSEncrypt object
var txPubKey = txJ$(".zwitch_encryptionkey").val();
var txEncrypter = new JSEncrypt();
txEncrypter.setPublicKey(txPubKey);
//get Data and encrypt it
var txData = '{}';
var txCryptData = '';
if(txJ$(".zwitch_data").length > 1)
{ //if there are more than one element with this class, convert it to json string
txData = txJ$(".zwitch_data").serializeObject();
txCryptData = txEncrypter.encrypt(JSON.stringify(txData));
}
else
{ //else, just encrypt the value
txData = txJ$(".zwitch_data").val();
txCryptData = txEncrypter.encrypt(txData);
}
dataString = txCryptData; // array?
$.ajax({
type: "POST",
url: "tokenize.php",
data: {data : dataString},
cache: false,
success: function(data) {
returnedvalue = data;
console.log(data); //alert isn't for debugging
}
});
alert(dataString);
}
I could get the value of dataString.But the ajax parrt is not working.I have added the jquery library.But doesnt seem to work
What's the error you are getting?
I think this should be:
$.ajax({
type: "POST",
url: "tokenize.php", //removed the dot
.....

Categories