How to do an if/then in to handle if a Parameter isn't being passed to the api
-
08-02-2021 - |
Question
I have a SharePoint 2016 page that expects a parameter and dynamically builds the url for the API call based on that parameter.
But, I'm struggling with what/how to do an if/then in my ajax to handle if no parameter is sent to the page.
Is it even possible to do an if/then in the AddFeatureSuggestion function to change the url for the api call?
This is the specific line I'd like to be able to set in the if/then:
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName2 + "')/items?$filter=SitePath eq '/sites/" + siteUrlFromParameter + "'"
Here's my code so far:
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
function getUrlParam(parameter, defaultvalue){
var urlparameter = defaultvalue;
if(window.location.href.indexOf(parameter) > -1){
urlparameter = getUrlVars()[parameter];
}
return urlparameter;
function addFeatureSuggestion() {
var siteUrlFromParameter = getUrlParam('Title', _spPageContextInfo.webAbsoluteUrl);
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName2 + "')/items?$filter=SitePath eq '/sites/" + siteUrlFromParameter + "'",
});
Solution
Yes you can do it like this:
var restEndpointUrl;
var siteUrlFromParameter = getUrlParam('Title', '');
if(siteUrlFromParameter) {
//write code for setting URL when parameter is passed to your page
restEndpointUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName2 + "')/items?$filter=SitePath eq '/sites/" + siteUrlFromParameter + "'"
} else {
//handle case when the parameter is not passed to your page
}
$.ajax({
url: restEndpointUrl,
...
});
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange