We help IT Professionals succeed at work.

REST api postCatgory showing as object

581 Views
Last Modified: 2015-10-06
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?
Comment
Watch Question

Rajendra ShekhawatSolution Architect

Commented:
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

IsaacSharePoint Client Side Developer

Author

Commented:
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 ShekhawatSolution Architect

Commented:
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
IsaacSharePoint Client Side Developer

Author

Commented:
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
IsaacSharePoint Client Side Developer

Author

Commented:
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 ShekhawatSolution Architect

Commented:
Hi,

Were you able to get the results for community count ?

Cheers,
Raj
IsaacSharePoint Client Side Developer

Author

Commented:
Hi Raj,

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

Commented:
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
IsaacSharePoint Client Side Developer

Author

Commented:
Ok. I just sent you an email with all the information you need.
Thanks so much for doing this.
Solution Architect
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
IsaacSharePoint Client Side Developer

Author

Commented:
Thanks a lot! That makes sense.
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.