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');
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'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);
I have an ASP.Net MVC Application and I got a JSON response from the server using this code segment.
public JsonResult GetVehicleByID(string VehicleID)
{
db.Configuration.ProxyCreationEnabled = false;
var res = from type in db.Vehicles
where type.ID == VehicleID
select new
{
ID = type.ID,
RegNo = type.RegNo
};
return Json(res, JsonRequestBehavior.AllowGet);
}
The code above returns the following Json (Google Postman)
[
{
"ID": "000001",
"Type": "Internal"
}
]
I handled the response using following jQuery Ajax
function GetVehicle(id) {
$.ajax({
async: true,
url: "GetVehicleByID?VehicleID=" + id,
cache: false,
dataType: "json",
contentType: "application/json",
success: function (data) {
//Parsing Method 1
//var a = jQuery.parseJSON(data);
//console.log(a.Type);
//Parsing Method 2
var b = $.parseJSON(data);
console.log(b['Type']);
}
});
}
I was unable to extract the Type element from this response. There are several similar questions in the Stack Overflow & solutions of those questions are about parsing. I tried to parse in 2 ways but the browser log gives following error
Uncaught SyntaxError: Unexpected token o in JSON at position 1
Helping is highly appreciated than flagging this question as duplicate.
Try just console.log(data[0].Type). I believe jQuery is already parsing the response as JSON for you because you specified dataType: "json" and the response from the server had the right Content-Type header.
As #smarx said jQuery already decoded json for you, so you can access directly to the Type from the data variable, but if not, you can parse the json response with the JS function parse:
var json_data = JSON.parse(data);
console.log(json_data);
I have a JSON response as the follwoing, but my problem is there are some characters that is not related to the JSON response I want. So I have pass that JSON response to a JavaScript variable and look into the JSON string. That is at the bottom.
-----------JSON Response------------
{
"readyState":4,
"responseText":"<?xml version=\"1.0\"encoding=\"utf-8\"?>\r\n<string>{\"kind\":\"analytics#gaData\",\"id\":\"https://www.googleapis.com/analytics/v3/data/ga?ids=ga:76546294&dimensions=ga:userType&metrics=ga:users&start-date=2014-10-01&end-date=2014-10-23&max-results=10\",\"query\":{\"start-date\":\"2014-10-01\",\"end-date\":\"2014-10-23\",\"ids\":\"ga:76546294\",\"dimensions\":\"ga:userType\",\"metrics\":[\"ga:users\"],\"start-index\":1,\"max-results\":10},\"itemsPerPage\":10,\"totalResults\":2,\"selfLink\":\"https://www.googleapis.com/analytics/v3/data/ga?ids=ga:76546294&dimensions=ga:userType&metrics=ga:users&start-date=2014-10-01&end-date=2014-10-23&max-results=10\",\"profileInfo\":{\"profileId\":\"76546294\",\"accountId\":\"289147\",\"webPropertyId\":\"UA-289147-1\",\"internalWebPropertyId\":\"456104\",\"profileName\":\"US - Institutional Investors - NP Microsite\",\"tableId\":\"ga:76546294\"},\"containsSampledData\":false,\"columnHeaders\":[{\"name\":\"ga:userType\",\"columnType\":\"DIMENSION\",\"dataType\":\"STRING\"},{\"name\":\"ga:users\",\"columnType\":\"METRIC\",\"dataType\":\"INTEGER\"}],\"totalsForAllResults\":{\"ga:users\":\"1110\"},\"rows\":[[\"New Visitor\",\"826\"],[\"Returning Visitor\",\"284\"]]}</string>",
"status":200,
"statusText":"OK"
}
-----------End of JSON ------------
I want to remove these characters from the beginning of the string:
`{"readyState":4,"responseText":"<?xml version=\"1.0\"encoding=\"utf-8\"?>\r\n<string>`
And I want to remove these character from the end of the string:
`</string>","status":200,"statusText":"OK"}`
So I want to remove these characters. I think a set of JavaScript String functions to be used. But I don't know how to mix them and use.
Could someone help me to solve this matter?
Thanks and regards,
Chiranthaka
UPDATE
I have used the follwoing AJAX function to send and get the JSON response back.
function setJsonSer() {
formData = {
'Email': 'clientlink#site.com',
'Password': 'password1234',
'URL': getVaria()
};
$.ajax({
url: "/APIWebService.asmx/AnalyticsDataShowWithPost",
type: 'POST',
data: formData,
complete: function(data) {
var jsonResult = JSON.stringify(data);
alert(JSON.stringify(data));
Load(data);
}
});
}
UPDATE 02
function setJsonSer() {
formData = {
'Email': 'clientlink#russell.com',
'Password': 'russell1234',
'URL': getVaria()
};
$.ajax({
url: "/APIWebService.asmx/AnalyticsDataShowWithPost",
type: 'POST',
data: formData,
dataType: 'json',
complete: function(data) {
var jsonResult = JSON.stringify(data);
alert(jsonResult);
Load(data);
}
});
}
I looked at your code:
complete: function(data) {
var jsonResult = JSON.stringify(data);
alert(jsonResult);
Load(data);
}
So you want to stringify your customized result, but your result is not well parsed JSON*? If yes then:
complete: function(data) {
var responseText = data.responseText;
var responseJson = JSON.parse(responseText.match(/[{].*.[}]/));
// you can skip `JSON.parse` if you dont want to leave it as `String` type
alert(JSON.stringify(responseJson)); //or just `responseJson` if you skip `JSON.parse`
Load(JSON.stringify(responseJson));
}
This can solve your problem for a while. But I think the problem is in your backend which did not serve well parsed JSON data. My recommendation is fixing your backend system first.
*Not well parsed JSON because your result some kind of including XML type of string under JSON object.
You have to parse JSON to get stuff which is inside it (You have
done this)
You have to parse the XML to get text which is inside the XML
Here's sample code for XML parsing:
http://www.w3schools.com/xml/tryit.asp?filename=tryxml_parsertest2