Access Field Values from JSON serialized django object - javascript

I have a problem which is proving to be harder to find an answer for than I imagined. I am using AJAX to update the select options based on a response from another select box. I am able to correctly retrieve the right list of objects, serialized as json, but I can't access any of the field values of the object.
View:
def choose_group(request):
team_id = request.POST['team_id']
groups = WorkoutGroup.objects.filter(team_id=team_id)
data = serializers.serialize('json', groups)
return HttpResponse(data, content_type='application/json')
Javascript/jQuery:
$('#team').on('change', function(){
var team_id = $(this).val();
$.ajax({
type: 'POST',
url: '/create_workout/choose_group/',
dataType: 'json',
async: true,
data: { csrfmiddlewaretoken:'{{ csrf_token }}', team_id: team_id },
success: function(data) {
var groups = $('#group');
$(groups).children().not(':first').remove();
if (data.length >= 1){
$.each(data, function(group){
$(groups).append('<option value=' + group['fields']['id'] + '>' + group['fields']['group_name'] + '</option>');
});
}
}
});
})
I get an error with all the ways I've tried to access the fields of each object (such as the id and group_name of the objects, as defined in the model). The error is 'cannot read property of undefined'.
EDIT:
I have also tried just creating a ValueQuerySet and dumping it using simplejson, but I still cannot access any fields within, just 'undefined'. Also, if I alert through each group, I get just the index of the iteration within the group list.
New View:
def choose_group(request):
team_id = request.POST['team_id']
groups = WorkoutGroup.objects.filter(team_id=team_id).values('id','group_name')
#data = serializers.serialize('json', groups)
return HttpResponse(simplejson.dumps(list(groups)), content_type='application/json')
and my Javascript now looks like this:
$('#team').on('change', function(){
var team_id = $(this).val();
$.ajax({
type: 'POST',
url: '/create_workout/choose_group/',
dataType: 'json',
async: true,
data: { csrfmiddlewaretoken:'{{ csrf_token }}', team_id: team_id },
success: function(groups_list) {
var groups = $('#group');
$(groups).children().not(':first').remove();
if (groups_list.length >= 1){
//json = JSON.parse(data);
$.each(groups_list, function(group){
alert(group)
$(groups).append('<option value=' + group.pk + '>' + group.fields.group_name + '</option>');
});
}
}
});
})

Accessing the serialized django object
To access the serialized django object you need to first parse the data variable like this:
var obj = JSON.parse(data);
And then you can access the fields of each object Individually like this:
// for the first object
obj[0]['fields']['id'] // or obj[0].fields.id
obj[0]['fields']['group_name'] // or obj[0].fields.group_name
// for the second object
obj[1]['fields']['id'] // or obj[1].fields.id
obj[1]['fields']['group_name'] // or obj[1].fields.group_name
// and so on...
In your case you can do this:
$.each(obj, function(index){ // for each object
$(groups).append('<option value=' + obj[index]['fields']['id'] + '>'+ obj[index]['fields']['group_name'] + '</option>');
});

Related

How Show data from for a miltiple list return by JSON funtion?

My Models:
ClassAllocate: Id, DepartmentId, CourseId, RoomId, DayId, StartTime, EndTime
Course: Id, CourseCode, CourseName, DepartmentId
Room: Id, RoomNumber
Day: Id, DayName
I am trying to search courses by department ID from "ClassAllocates" table in view page and trying to display only those courses schedule/allocation details.
I am using JSON to send lists from controller to view. I need to send multiple lists of list from a JsonResult function. I can send them ( I tried to send 2 lists), but, I can't display them. it is showing [object Object] or nothing or undefined in my attempts.
I am including my Controller funtion and Javascript in view:
1st: Controller Function
public JsonResult GetCourseIdListByDepartmentId(int departmentId)
{
var x = db.ClassAllocates.DistinctBy(m => m.CourseId).Where(m => m.DepartmentId == departmentId).ToList();
var r = db.ClassAllocates.DistinctBy(m => m.RoomId).Where(m => m.DepartmentId == departmentId).ToList();
var all = new [] {x,r}.ToList();
return Json(all, JsonRequestBehavior.AllowGet);
}
2nd: View Java Script
<script>
$("#DepartmentId").change(function () {
var dptId = $("#DepartmentId").val();
//alert(dptId);
$(".RowClass").empty();
var json = {
departmentId: dptId
};
$.ajax({
type: "POST",
url: '#Url.Action("GetCourseIdListByDepartmentId", "ClassAllocates")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(json),
success: function (data) {
$.each(data, function (key, value) {
$(".table2").append(
'<tr class="RowClass">' +
'<td>' + value.Couse + '</td>'
+ '<tr>');
});
}
});
});
This result in:
undefined
I need, CourseCode, CourseName and RoomNumber
I got a way. As JSON returns List or list, then I need to write for loop twice after JSON success in View code or client side code.
$.each(data, function (key, value) {
if (key==0) {
$.each(this, function (k, v) {
$(".table2").append(
'<tr class="RowClass">' +
'<td>' + v.Course.CourseCode + '</td>'
+ '<tr>');
});
}
});
Now I am trying to pass and get more complex data.

How to show/print property name of each items/Objects that were taken from database with AJAX

I am starting to learn how to use Ajax, and get JSON objects from database.
So far i have this
$('.myButton').click(function () {
var printInfo = document.getElementById('printInfo').value;
var load = document.getElementById('Loading');
load.style.display = 'block';
$.ajax({
'url': ......,
//The type of request, also known as the "method" in HTML forms
//Can be 'GET' or 'POST'
'type': 'GET',
'success': function (data) {
document.write(data);
load.style.display = 'none';
//pisi tuka html kod
}
});
});
So, when i have those items received from the database it show me like this
[object Object],[object Object],[object Object]
How to take the property of each object? Like, if i write pizza, in the input, and to print like "Pepperoni Pizza", "Cheese, pizza","Pan pizza, crust only"
$('.myButton').click(function () {
var printInfo = document.getElementById('printInfo').value;
var load = document.getElementById('Loading');
load.style.display = 'block';
$.ajax({
'url': ..... + printInfo,
//The type of request, also known as the "method" in HTML forms
//Can be 'GET' or 'POST'
'type': 'GET',
'success': function (data) {
var text = "";
// Cycle each property in object data
for (var prop in data) {
text += "data." + prop + " = " + data[prop] + "<br>";
}
document.write(text);
load.style.display = 'none';
//pisi tuka html kod
}
});
});

How to post a form with ajax and return data in array?

HI how to post a form and return data it will be a array as like this
{
"notes":'some notes',
"validUntil": '12/12/2015',
"status": 1,
"menuItemName": "HR Section",
"menuItemDesc": "gggg"
}
My code is this
$('#add-menu-list .btn[data-attr=submit-btn]').on('click', function(){
var formValidate = $('#add-menu-list').parsley().validate();
validateFront();
// console.log(formValidate);
var menuName = $('input[data-api-attr=menuItemName]').val();
var validUntil = $('input[data-api-attr=validUntil]').val();
var menuStatus = $('input[data-api-attr=status]').val();
var menuNote = $('textarea[data-api-attr=notes]').val();
var menuDesc = $('textarea[data-api-attr=menuItemDesc]').val();
var dataString = {
menuItemName: menuName,
validUntil : validUntil,
status : menuStatus,
notes : menuNote,
menuItemDesc : menuDesc
};
if(formValidate == true){
alert('success');
console.log(menuName + validUntil + menuStatus + menuNote + menuDesc);
var url = "xyz.html"; // the script where you handle the form input.
$.ajax({
type: "POST",
// url: url,
dataType: "json",
data: $(dataString).serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response
}
});
}else{
alert('Validation fail ');
}
});
Since "data" is a server response i guess that your server return a json object. In this case you have to somehow inform the jquery's ajax that you expect a json response from server or you have to translate the "data" to a json object by your self.
It is best to follow the first option so you don t have to deal with the translation your self you can easily do that by giving an extra parameter tou your ajax reuest : dataType: 'json', this will do the trick!
Now that you have a proper response object from your request you can either stringify it with var string_resp=JSON.stringify(data); and then alert it alert(string_resp) or you can access its elements like that : alert(data.status) which will alert your object's status field etc.
so your code will be :
$.ajax({
type: "POST",
url: url,
dataType: 'json',
data: $(menuName).serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // will alert an object
alert(data.status); // will alert object's status field in this case 1
alert(JSON.stringify(data)) // will alert the object as a string
}
});
you are sending only one value in serialize, serialize() should be on form element not on field element, like :
$('#add-menu-list .btn[data-attr=submit-btn]').on('click', function(){
...
$.ajax({
...
data:$("#form").serialize();
...
success: function(data)
{
alert(data.notes); // show response
....
}
var myObj = {
"notes":'some notes',
"validUntil": '12/12/2015',
"status": 1,
"menuItemName": "HR Section",
"menuItemDesc": "gggg"
};
myObj.toString = function()
{
var str = '';
for (var property in myObj)
{
if (myObj.hasOwnProperty(property) && (property != "toString") )
{
str += (property + ': ' + myObj[property] + "\n");
// do stuff
}
}
return str;
}
alert(myObj);

sharepoint rest lookup value

i'm having a minor issue. I'm using REST/JS to populate a dropdown box, which requires first getting the lookup of a column in a list.
//Product Model Cascade
document.getElementById("productDD").onchange = function() {
var prod = this.options[document.getElementById("productDD").selectedIndex].text;
var select = document.getElementById("productModelDD");
$(select).empty();
var call2 = $.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists(guid'bb392616-24ee-47e2-9365-f17400348373')/Items", //the list
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
call2.done(function(data, textStatus, jqXHR) {
var select = document.getElementById("productModellDD");
for (index in data.d.results) {
var parent = data.d.results[index].AT_ARMATECproducts; //Lookup column
console.log("parent var: " + parent);
if (parent == prod) {
var op = document.createElement("option");
op.text = data.d.results[index].Title;
op.value = data.d.results[index].Title;
select.appendChild(op);
}
}
});
}
but the parent value is coming back as "undefined" and i've triple checked that this is the correct list. I've also tried .get_LookupValue() but it comes back as can't get it from an undefined field.
So how do you get the value of a lookup field via rest?
EDIT:
I have done select/expand in the REST Query but have come up with a 400 bad request error:
url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists(guid'bb392616-24ee-47e2-9365-f17400348373')/items?$select=Title,AT_ARMATECproducts/Title&$expand=AT_ARMATECproducts/Title",
Where AT_ARMATECproducts is the lookup field in the ARMATEC Product Models List. AT_ARMATECproducts is a lookup to the ARMATEC Products list which grabs the titles.
So, it turns out the lookup list was under a different name for some reason, it the list it shows up as AT_ARMATECproducts but seems to actually be AT_Products1.
url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists(guid'bb392616-24ee-47e2-9365-f17400348373')/items?$select=Title,AT_Products1/Title&$expand=AT_Products1/Title",
var parent = data.d.results[index].AT_Products1;
now returns [object object], when I tried .Titles it returned with the Titles of the List not the lookup list. And when I tried .AT_Products1.Title it returned with undefined.
When working with User/Lookup field values via SharePoint REST API it is important to differentiate between single-valued and multi-valued lookup fields.
Single-valued lookup fields
Assume Employee list with a single-valued lookup field Department
Then the query: /_api/web/lists/getbytitle('<list title>')/items returns lookup Id, for example:
getListItems(_spPageContextInfo.webAbsoluteUrl,'','Employees',
function(items){
if(items.length > 0)
console.log(items[0].DepartmentId); //returns LookupId
},
function(error){
console.log(error.responseText);
});
The query:
/_api/web/lists/getbytitle('Employees')/items?$select=Department/Title,Department/Id&$expand=Department
returns projected Department object as shown below:
getListItems(_spPageContextInfo.webAbsoluteUrl,'?$select=Department/Title,Department/Id&$expand=Department','Employees',
function(items){
if(items.length > 0)
console.log(items[0].Department.Title);
console.log(items[0].Department.Id);
},
function(error){
console.log(error.responseText);
});
Multi-valued lookup fields
Assume Employee list with a multi-valued lookup field Departments
Then the query: /_api/web/lists/getbytitle('<list title>')/items returns an array of lookup ids, for example:
getListItems(_spPageContextInfo.webAbsoluteUrl,'','Employees',
function(items){
if(items.length > 0)
console.log(items[0].DepartmentsId); //returns an array [LookupId1, LookupId1 .. LookupIdN]
},
function(error){
console.log(error.responseText);
});
The query:
/_api/web/lists/getbytitle('Employees')/items?$select=Departments/Title,Departments/Id&$expand=Departments
returns projected Departments array of objects as shown below:
getListItems(_spPageContextInfo.webAbsoluteUrl,'?$select=Departments/Title,Departments/Id&$expand=Departments','Employees',
function(items){
if(items.length > 0)
if(items[0].Departments.results.length > 0) {
console.log(items[0].Departments.results[0].Title);
console.log(items[0].Departments.results[0].Id);
}
},
function(error){
console.log(error.responseText);
});
SharePoint 2013 REST read operation function:
function getListItems(url, query, listName, success, failure) {
$.ajax({
url: url + "/_api/web/lists/getbytitle('" + listName + "')/items" + query,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
success(data.d.results);
},
error: function (data) {
failure(data);
}
});
}
Try
/_api/Web/Lists(guid'bb392616-24ee-47e2-9365-f17400348373')/items?$select=Title,AT_ARMATECproducts/Title&$expand=AT_ARMATECproducts"
as you endpoint
The expand query should only contain the title of the lookup column, and should not include the lookup field. Your select is fine, but the expand isn't.
below query finally worked for me
Merged is a calculated field in Cats list
Cat is a lookup field(which looks above Merged column) in the MainFlat list
"?$select=Title,number,Cat/Merged&$expand=Cat" +
"&$filter=Cat/Merged eq '"+Merged+"' "
https://sharepoint.stackexchange.com/a/152997/16880

How to pass cakephp formhelper input values to ajax via jquery?

I am still new to cakephp, and my attempt is to retrieve the FormHelper's value and pass it via $.ajax() call in jquery. However, by cakephp convention, the name of each field generated by FormHelper will be in the format of data[Model][field]. Now, I want to submit $_POST data in form of cakephp array format. However, I couldn't find a way to do so, because I couldn't find a way to turn name and value attribute into a passable array format.
My attempt was to turn everything into string and try to create a json array. However, I failed to do so, and this method doesn't seem convincing to me too.
function submitEdit(sendurl, formid){
var dataset = [];
$('form#'+ formid + ' > input,select').each(function(){
dataset.push($(this).attr('name') + ':' + $(this).val());
});
alert(dataset);
$.ajax({
type: 'POST',
data: '{' + dataset + ']',
url: sendurl,
success: function(content){
$('.setting-preview.username').append('<pre>' + content + '</pre>');
}
});
}
Therefore, how do I pass this as data[Model][field] array to the sendurl controller?
Something like
$.ajax({
type: 'POST',
data: {
Model: {
foo: $('#ModelFoo').val(),
bar: $('#ModelBar').val()
}
},
url: sendurl,
success: function(content){
$('.setting-preview.username').append('<pre>' + content + '</pre>');
}
});

Categories