Link to home
Start Free TrialLog in
Avatar of Isaac
IsaacFlag 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
User generated image
Any ideas?
Avatar of Rajendra Shekhawat
Rajendra Shekhawat
Flag of India image

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

Avatar of 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
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
Avatar of 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
Avatar of 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
User generated image
	$(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

Hi,

Were you able to get the results for community count ?

Cheers,
Raj
Avatar of Isaac

ASKER

Hi Raj,

No. Actually, the image that has the Category shouldn't be 0, it should be categories (javaScript, HTML, SharePoint, etc.)
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
Avatar of Isaac

ASKER

Ok. I just sent you an email with all the information you need.
Thanks so much for doing this.
ASKER CERTIFIED SOLUTION
Avatar of Rajendra Shekhawat
Rajendra Shekhawat
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Isaac

ASKER

Thanks a lot! That makes sense.