XMLHttpRequest is not defined error - REST

brostoff17
Tera Contributor

I am trying to do a POST request via REST.   I code the same javascript from the REST Explorer in ServiceNow, but am getting a "XMLHttpRequest is not defined" (line 7) error when I try and run the code in a workflow script.   Any ideas how to fix this?

var token = "XXX";

var currentEmail = current.variables.email;

var channels = current.variables.channels;

var requestBody = "";

var client = new XMLHttpRequest();

client.open("post",'https://slack.com/api/users.admin.invite?token=' + token + '&' + 'email=' + currentEmail + '&' + 'channels=' + channels);

client.setRequestHeader('Accept','application/json');

client.setRequestHeader('Content-Type','application/json');

//Eg. UserName="admin", Password="admin" for this code sample.

//client.setRequestHeader('Authorization', 'Basic '+btoa('admin'+':'+'admin'));

client.onreadystatechange = function() {

if(this.readyState == this.DONE) {

document.getElementById("response").innerHTML=this.status + this.response;

}

};

client.send(requestBody);

1 ACCEPTED SOLUTION

Bryan Tay3
Mega Guru

hi Josh,



Have you tried the rest api code from ServiceNow Scripts?


find_real_file.png


Mine working just find.



find_real_file.png


Code:


var request = new sn_ws.RESTMessageV2();


request.setEndpoint('https://your_instance_name.service-now.com/api/now/table/incident?sysparm_limit=1');


request.setHttpMethod('GET');



//Eg. UserName="admin", Password="admin" for this code sample.


var user = 'xxxxxxx';


var password = 'xxxxxx';



request.setBasicAuth(user,password);


request.setRequestHeader("Accept","application/json");



var response = request.execute();


gs.log(response.getBody());



Hope this helps.


View solution in original post

2 REPLIES 2

lakshminarayan4
ServiceNow Employee
ServiceNow Employee

Hi,


The script is running from server context. So XMLHTTPRequest is only available in browser only. you can use REST API.





Outbound REST Web Service - ServiceNow Wiki




Thanks


Bryan Tay3
Mega Guru

hi Josh,



Have you tried the rest api code from ServiceNow Scripts?


find_real_file.png


Mine working just find.



find_real_file.png


Code:


var request = new sn_ws.RESTMessageV2();


request.setEndpoint('https://your_instance_name.service-now.com/api/now/table/incident?sysparm_limit=1');


request.setHttpMethod('GET');



//Eg. UserName="admin", Password="admin" for this code sample.


var user = 'xxxxxxx';


var password = 'xxxxxx';



request.setBasicAuth(user,password);


request.setRequestHeader("Accept","application/json");



var response = request.execute();


gs.log(response.getBody());



Hope this helps.