2

I am creating a subiste by using the below javascript code.I want to check if a subsite exists or not before creating it. I ma creating a susiste on button click function like below

<div>
<input type="test" id="text" /><input type="button" id="button" value="Create Site " />
</div>

$('#button').click(function() {
    var mytest= $("#text").val();
    alert(mytest);
    createWebsite(mytest);

});

Can any one help me on this .

Creating a subsiste function

     function createWebsite(SiteName) {

        var clientContext = SP.ClientContext.get_current();;
        var collWeb = clientContext.get_web().get_webs();
        var webCreationInfo = new SP.WebCreationInformation();
        webCreationInfo.set_title(SiteName);
        webCreationInfo.set_description('Description of new Web site...');
        webCreationInfo.set_language(1033);
        webCreationInfo.set_url(SiteName);
        webCreationInfo.set_useSamePermissionsAsParentSite(true);
        webCreationInfo.set_webTemplate(siteTemplate);
          var oNewWebsite = collWeb.add(webCreationInfo);
        clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
    }

    function onQuerySucceeded() {
        alert("Created Web site.");
    }

    function onQueryFailed(sender, args) {
        alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }
Dikesh Gandhi
  • 6,803
  • 4
  • 30
  • 55
santosh kondapalli
  • 892
  • 2
  • 23
  • 60

2 Answers2

2

You can get all sub sites with title and server-relative url using below code. Then you can perform title/url check step to check if sub site is exist or not.

function getWebs()
{
   var context = SP.ClientContext.get_current();
   var web = context.get_web(); 
   var site = context.get_site();
   var rootWeb = site.get_rootWeb();
   var subWebs = rootWeb.get_webs();

   context.load(subWebs, 'Include(Title, ServerRelativeUrl,ParentWeb)');
   context.executeQueryAsync(
    function () {  
         for (var i = 0; i < subWebs.get_count(); i++) {
            var subWeb = subWebs.itemAt(i);
            var parentWeb = subWeb.get_parentWeb();  //parent web ==  root web
            console.log(subWeb.get_title());

            //Here You can get all sub-sites title, you can put here logic to compare the name for new subsite 
          }
    },
    function (sender, args) {
       console.log(args.get_message());
    }
   );   
}

Reference:

Dikesh Gandhi
  • 6,803
  • 4
  • 30
  • 55
1

You can use the REST API's getsubwebsfilteredforcurrentuser method to check for the subsite's title and then create the site if it doesn't exist.

Try the below code:

$('#button').click(function() {
    var mytest= $("#text").val();
    CheckSubSiteExistsIfNotCreate(mytest);    
});

function CheckSubSiteExistsIfNotCreate(mytest){
    $.ajax({
            url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/getsubwebsfilteredforcurrentuser(nwebtemplatefilter=-1,nconfigurationfilter=0)?$select=Title&$filter=substringof('"+mytest+"', Title)",
            method: "GET",
            headers: { "Accept": "application/json; odata=verbose" },
            success: function (data) {
                if(data.d.results.length>0){
                    console.log("site exists");
                }
                else{
                    createWebsite(mytest);
                }

            },
            error: function (data) {
                console.log(data);
            }
      }); 
}

function createWebsite(SiteName) {

    var clientContext = SP.ClientContext.get_current();;
    var collWeb = clientContext.get_web().get_webs();
    var webCreationInfo = new SP.WebCreationInformation();
    webCreationInfo.set_title(SiteName);
    webCreationInfo.set_description('Description of new Web site...');
    webCreationInfo.set_language(1033);
    webCreationInfo.set_url(SiteName);
    webCreationInfo.set_useSamePermissionsAsParentSite(true);
    webCreationInfo.set_webTemplate(siteTemplate);
    var oNewWebsite = collWeb.add(webCreationInfo);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded() {
    console.log("Created Web site.");
}

function onQueryFailed(sender, args) {
    console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

Here i am using both REST API and JSOM. Many people, like me, dont like this combination since it "breaks consistency". But hey, whatever works. The above answer is also correct but this approach is a bit more efficient as it uses REST API filters instead of iterating over a list of subsites.

getsubwebsforcurrentuser provides you with a security trimmed list of subsites for which user has access.

If you want to create a subsite using REST API, you can follow this excellent link to have "consistency" - Create subsite in 2013 using REST API

Reference - SP.Web.getSubwebsForCurrentUser Method

Gautam Sheth
  • 30,881
  • 1
  • 35
  • 62
  • getsubwebsforcurrentuser will provide only those sites on which user has access, if user don't have access on the site 'A' so he cannot see/get the site and when user will proceed for creation of the same name site then it may give error for "same name/URL site already exist" . Is that right? – Dikesh Gandhi Mar 08 '17 at 16:36