How to pass dynamic values to variables for cart item in cartjs in scripted REST API?

Annamdevula Di1
Kilo Contributor

Hi All,

How to pass dynamic values for variables in scripted REST API for creating cart item by using cartjs API. Can you please suggest  this.

find_real_file.png

12 REPLIES 12

Voona Rohila
Mega Patron
Mega Patron

Hi Divya

How are you bring values dynamically?

Sample :

   'variables':{
                'variable1': "1",
                'variable2': reqbody.xyz,
                'variable3': reqbody.abc,
            }

Mark it helpful if this helps you to understand. Accept solution if this give you the answer you're looking for
Kind Regards,
Rohila V
2022-25 ServiceNow Community MVP

Hi Rohila,

Thank you so much for reply.I have edited the code as given below, but variables are not replicating, cart item is creating, butI dont know where I went wrong as I am new to servicenow.

 

(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
gs.log(request);
gs.log(response);
var reqbody = request.body.data;
try{
var parser = new global.JSON();
var parsedData = parser.decode(reqbody);
var memoryvar = parsedData.memory;
var colourvar = parsedData.colour;
// implement resource here
var Mobilecart = GlideGuid.generate(null);
var cart = new sn_sc.CartJS("Testlaptop");
var item =
{
'sysparm_id': '75e7a257dbd1011052939026ca9619bc',
'sysparm_quantity': '1',
'variables':{
'memory' : reqbody.Memory,
'colour': reqbody.Colour,
}};
var cartDetails = cart.addToCart(item);
gs.log(JSON.stringify(cartDetails));
var rc = cart.placeOrder();
}
catch(ex){
var res = {};
res["status"] = "Success";
res["message"] = ex.message;
response.setBody(JSON.stringify(res));
}

})(request, response);

Try below code.

looks like you are already storing the values in memoryvar,colourvar variables.

 

(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
gs.log(request);
gs.log(response);
var reqbody = request.body.data;
try{
var parser = new global.JSON();
var parsedData = parser.decode(reqbody);
var memoryvar = parsedData.memory;
var colourvar = parsedData.colour;
// implement resource here
var Mobilecart = GlideGuid.generate(null);
var cart = new sn_sc.CartJS("Testlaptop");
var item =
{
'sysparm_id': '75e7a257dbd1011052939026ca9619bc',
'sysparm_quantity': '1',
'variables':{
'memory' : memoryvar,
'colour': colourvar,
}};
var cartDetails = cart.addToCart(item);
gs.log(JSON.stringify(cartDetails));
var rc = cart.placeOrder();
}
catch(ex){
var res = {};
res["status"] = "Success";
res["message"] = ex.message;
response.setBody(JSON.stringify(res));
}

})(request, response);


Mark it helpful if this helps you to understand. Accept solution if this give you the answer you're looking for
Kind Regards,
Rohila V
2022-25 ServiceNow Community MVP

I have tried this code too, even its not passing the values.