\$sp.getParameter("sys_id") returning "null" value in Service portal

DUGGI
Giga Guru

I am using $sp.getParameter("sys_id") in widget ,but it retun null,

anyone can help on this ?

15 REPLIES 15

Admin Pro
Tera Contributor

Thank you, Scott! That makes a total sense. I have used the clientData in the past, never thought of its use case on a widget. Clever thinking


If you're still stuck, try this in the client script of your widget....



c.getResults = function(query) {
  var catalogItemSysId = getParameterByName('sys_id');
  return c.server.get({q: query, sysid: catalogItemSysId}).then(function(response) {
    console.log(JSON.stringify(response.data.results));
    return response.data.results;
  });
}


function getParameterByName(name, url) {
      if (!url) url = window.location.href;
      name = name.replace(/[\[\]]/g, "\\$&");
      var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
              results = regex.exec(url);
      if (!results) return null;
      if (!results[2]) return '';
      return decodeURIComponent(results[2].replace(/\+/g, " "));
}



This will pass an object called input with input.q (presumably from something in your widget like a drop down box) along with input.sysid containing the sysid as taken from the URL. On the server side, whatever you push into data.results will be written to the browser console for you to inspect



Hope that helps.


Thanks Peter, Scott's idea worked just fine.


And if anyone else is still stuck due to their bare-bones understanding of js classes, just swap out the GlideUtilSession calls with the built-in script includes from ServiceNow like so:


// grab the data as normal:
var mySysParm = $sp.getParameter("sysparm_WHATEVER");      

// declare the reusable variable for use in script later
var usableSysParm;  

if (mySysParm   != null ) {
//   save value for record watcher as $sp not maintaining GET vars from initial page load.          
// (due to request to model in the background).          

gs.getSession().putClientData('sysparm_WHATEVER', mySysParm);

} else {        
// after any input the original $sp.getParameter value becomes permanently null,          
// so grab from the "session variables":                  

if (input) {                              
usableSysParm = gs.getSession().getClientData('sysparm_WHATEVER');                    
}
}

Keep on trucking, truckers!



(PS: you'll have to indent it yourself. my n008iness knows no bounds.)


The solution with Session works nicely ONLY if you have single tab open. In certain case when more than tabs are open (and the url parameters are used), this wouldn't work.