In this blog I would like to share code to get the content type collection from APP host web in SharePoint Hosted app using JavaScript Object Model.

  1. var ctx;
  2. var appCtxSite;
  3. var contentTypeCollection;
  4. var contentType;
  5. var hostWebURL;
  6. var appWebURL;
  7. var contentTypeName;
  8. var ContentTypeID;`
  9. var ContentTypeEnumerator;
  10. $(document).ready(function () {
  11. // debugger;
  12. //// Get the URI decoded URLs.
  13. hostWebUrl = decodeURIComponent(manageQueryStringParameter('SPHostUrl'));
  14. appWebUrl = decodeURIComponent(manageQueryStringParameter('SPAppWebUrl'));
  15. //calling the getHostWeb method in ready function to get content type on when page is ready
  16. getHostWeb();
  17. });
  18. //This function is used to get the hostweb url
  19. function manageQueryStringParameter(paramToRetrieve)
  20. {
  21. var params = document.URL.split("?")[1].split("&");
  22. var strParams = "";
  23. for (var i = 0; i < params.length; i = i + 1)
  24. {
  25. var singleParam = params[i].split("=");
  26. if (singleParam[0] == paramToRetrieve)
  27. {
  28. return singleParam[1];
  29. }
  30. }
  31. }
  32. //get the list data from host web
  33. function getHostWeb()
  34. {
  35. //get current app web context
  36. ctx = new SP.ClientContext(appWebUrl);
  37. //get current host web context
  38. appCtxSite = new SP.AppContextSite(ctx, hostWebUrl);
  39. //get current host web
  40. if (ctx != undefined && ctx != null)
  41. {
  42. web = appCtxSite.get_web();
  43. }
  44. //// .load() tells CSOM to load the properties of this object
  45. ctx.load(web);
  46. ctx.executeQueryAsync(getContentTypeCollection, onQueryFailed);
  47. }
  48. function getContentTypeCollection()
  49. {
  50. //Get all content types from current app host web
  51. contentTypeCollection = web.get_contentTypes();
  52. //load the content type collection
  53. ctx.load(contentTypeCollection);
  54. ctx.executeQueryAsync(getallContentType, onQueryFailed);
  55. }
  56. function getallContentType()
  57. {
  58. ContentTypeEnumerator = contentTypeCollection.getEnumerator();
  59. var count = contentTypeCollection.get_count();
  60. if (count > 0)
  61. {
  62. //Get content type one by one
  63. while (ContentTypeEnumerator.moveNext())
  64. {
  65. contentType = ContentTypeEnumerator.get_current();
  66. contentTypeName = contentType.get_name();
  67. alert(contentTypeName);
  68. }
  69. }
  70. }
  71. function onQueryFailed(sender, args)
  72. {
  73. alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
  74. }
Summary

In this blog we have explored how to get the all content types from SharePoint Hosted web using JavaScript Object Model.

Happy Coding