Avatar of Isaac
Isaac
Flag for United States of America asked on

REST api postCatgory showing as object

I was able o successfully use $expand for two lists
$.ajax({
        url: url + "/_api/web/lists/getbytitle('" + listname + "')/items?$select=Created,Title,NumCommentsId,ID,PostCategory/Title&$expand=PostCategory",
        method: "GET",                                                      
        headers: { "Accept": "application/json; odata=verbose" },
		timeout: 2000,
		dataType:"json",
        success: function (data) {
            complete(data); // Returns JSON collection of the results
        },
        error: function (xhr,status,error) {
            console.log(status);
        }
    });

Open in new window

But when I try to access postCategory, I get an object.
for(var i =0; i < data.d.results.length; i++) 
		{		
			var imgStatus = (dateDiff(data.d.results[i].Created));
			if(imgStatus == "New")
			{
				imgCategory = "<img src='http://isaacsogunro.com/blog/Images1/yellowNew.png' alt='New'>";
			}
		    //bldRow.row.add([ dateFormat(data.d.results[i].Created), "<a href='#' onClick='openModal("+data.d.results[i].ID+");return false;'>"+data.d.results[i].Title+"</a>",/*data.d.results[i].NumCommentsId,*/imgCategory]).draw();				   
			bldRow.row.add([ dateFormat(data.d.results[i].Created), "<a href='http://isaacsogunro.com/blog/Lists/Posts/Post.aspx?ID="+data.d.results[i].ID+"'>"+data.d.results[i].Title+"</a>",data.d.results[i].PostCategory,/*data.d.results[i].Category,data.d.results[i].NumCommentsId,*/imgCategory]).draw();				   
		}

Open in new window



Here's what i get for postcategory
1postcategory.JPG
Any ideas?
RESTMicrosoft SharePointJavaScript

Avatar of undefined
Last Comment
Isaac

8/22/2022 - Mon
Rajendra Shekhawat

Hi,

PostCategory is an object with nested categories.
I tested your code and modified it to write it to console.

Attached code snippet.
Please test and let know, in case of any issues.

I hope it helps.

Cheers,
Raj

<script type='text/javascript' src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js'> </script>
<script type='text/javascript'>

var url = 'http://c4968397007/sites/blog';
var listname = 'posts';

$.ajax({

        url: url + "/_api/web/lists/getbytitle('" + listname + "')/items?$select=Created,Title,NumCommentsId,ID,PostCategory/Title&$expand=PostCategory",
        method: "GET",                                                      
        headers: { "Accept": "application/json; odata=verbose" },
		timeout: 2000,
		dataType:"json",
        success: function (data) {
            complete(data); // Returns JSON collection of the results
        },
        error: function (xhr,status,error) {
            console.log(status);
        }
    });

function complete(data)
{

   for(var i =0; i < data.d.results.length; i++) 
   {		
    console.log(data.d.results[i].Created);
    console.log(data.d.results[i].Title);
 
      for(category in data.d.results[i].PostCategory.results) {
            console.log(data.d.results[i].PostCategory.results[category].Title);
      }  //end of category loop
   }  //end of loop
}  //end of function

</script>

Open in new window

Isaac

ASKER
I got the following error: SCRIPT5009: 'category' is undefined

I then added 'category' to my rest:
items?$select=Created,Title,NumCommentsId,ID,Category,PostCategory/Title&$expand=PostCategory",

After that, I get error
Rajendra Shekhawat

Hi,

Category is not the field. PostCategory is the field. List of Categories is inside PostCategory object.
Code Snippet shared gives you list of categories.

Cheers,
Raj
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
Isaac

ASKER
When I had the following
items?$select=Created,Title,NumCommentsId,ID,PostCategory/Title&$expand=PostCategory"

Open in new window


I got this error:
SCRIPT5009: 'category' is undefined
Isaac

ASKER
Here's my whole code:
Here's what i'm trying to achieve:
As you can see, the Category column is 0. It needs to show the categories that was assigned to that post. ie: javascript, SharePoint, HTML 5, etc.

Two lists are being used, Posts and Categories.  Category column in the Post  list is a lookup into Categories
Category
	$(document).ready(function(){
		$('#blog').DataTable();

		getListItems('http://mysite/blog','Posts','complete', 'failure','timeout');
	});

//Change code to use this - http://datatables.net/examples/advanced_init/events_live.html
function getListItems(url, listname, complete, failure, timeout) {

    // Executing our items via an ajax request
	
    $.ajax({
        url: url + "/_api/web/lists/getbytitle('" + listname + "')/items?$select=Created,Title,NumCommentsId,ID,PostCategory/Title&$expand=PostCategory",
        method: "GET",                                                      
        headers: { "Accept": "application/json; odata=verbose" },
		timeout: 2000,
		dataType:"json",
        success: function (data) {
            complete(data); // Returns JSON collection of the results
        },
        error: function (xhr,status,error) {
            console.log(status);
        }
    });

	function complete(data) 
	{		
		var bldRow=$('#Iblog').DataTable({
			"order": [[ 0, "desc" ]],
			"pagingType": "full_numbers"
		});
				
		var imgCategory=" ";
		for(var i =0; i < data.d.results.length; i++) 
		{		
			var imgStatus = (dateDiff(data.d.results[i].Created));
			if(imgStatus == "New")
			{
				imgCategory = "<img src='http://mysite.com/blog/Images1/yellowNew.png' alt='New'>";
			}		   
			bldRow.row.add([ dateFormat(data.d.results[i].Created), "<a href='http://mysite.com/blog/Lists/Posts/Post.aspx?ID="+data.d.results[i].ID+"'>"+data.d.results[i].Title+"</a>",data.d.results[i].NumCommentsId,/*data.d.results[i].Category,data.d.results[i].NumCommentsId,*/imgCategory]).draw();				   
		}
	 }
	function failure(data) {
	 alert("Operation failed.");
	 }	 
}	

	function dateDiff(spCreated)
	{
		var createdDte = new Date(spCreated);
		var todayDate = new Date();
		var timeDiff = Math.abs(todayDate.getTime() - createdDte.getTime());
		var days = Math.ceil(timeDiff/(1000*3600*24));
		var status = (days > 30) ? "Old":"New";
			
		return status;
	}

	function dateFormat(spCreated)
	{
		var createdDte = new Date(spCreated);
		var newFormat = (createdDte.getMonth()+1)+"/"+(createdDte.getDate()+"/"+createdDte.getFullYear());
		
		return newFormat;
	}
	
	 function openModal(blogID) {
		var pageUrl = 'http://mysite.com/blog/Lists/Posts/Post.aspx?ID='+blogID;
		var options = { url: pageUrl, width: 650, height: 650 };

		SP.SOD.execute('sp.ui.dialog.js', 'SP.UI.ModalDialog.showModalDialog', options);

	 }

Open in new window

Rajendra Shekhawat

Hi,

Were you able to get the results for community count ?

Cheers,
Raj
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Isaac

ASKER
Hi Raj,

No. Actually, the image that has the Category shouldn't be 0, it should be categories (javaScript, HTML, SharePoint, etc.)
Rajendra Shekhawat

Hi,

Please send me complete code with html ( datatables.net etc. ). I would try to fix it.
My Email - rajendra.shekhawat@gmail.com
My Skype - rajendra.shekhawat

Cheers,
Raj
Isaac

ASKER
Ok. I just sent you an email with all the information you need.
Thanks so much for doing this.
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
ASKER CERTIFIED SOLUTION
Rajendra Shekhawat

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Isaac

ASKER
Thanks a lot! That makes sense.