Aryan Aryan - 6 months ago 10
JSON Question

JSON with variables in Javascript

I am trying to send Rest web service request with JSON. But it throws Bad request(http 400) error. The application does not require any login. I tried different formats, but nothing helped. The main problem is JSON variables are dynamic i.e values entered by user.

var jsonObject = [];
var first_name = document.getElementById("firstName").value;
var last_name = document.getElementById("lastName").value;
var u_password = document.getElementById("password").value;
var u_password_hint = document.getElementById("passwordHint").value;
var email = document.getElementById("email").value;
var u_phone = document.getElementById("phone").value;
var u_organization = document.getElementById("organization").value;

var user = new User(first_name,last_name,email,u_password,u_password_hint,u_organization);
jsonObject.push(user);

var client = new XMLHttpRequest();
client.open("POST","https://instance.service-now.com/api/now/v1/table/user_registration_request");
client.setRequestHeader('Accept','application/json');
client.setRequestHeader('Content-Type','application/json');
client.send(body);
window.location = 'activate account.do';

function User(first_name, last_name, email, u_password_hint, u_password, u_organization) {
this.first_name = first_name;
this.last_name = last_name;
this.email = email;
this.u_password = u_password;
this.u_password_hint = u_password_hint;
this.u_organization = u_organization;
}

Answer

After lot of trouble, I found the solution. Original JSON format works with small modifications.

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
 }
});
xhr.open("POST","https://instance.service-now.com/api/now/table/ecc_queue");

var data='{"agent":"AttachmentCreator","topic":"AttachmentCreator","name":"'+fileName+'","source":"u_itinerary_attchements:"'+sysid+'","payload":"'+encodedFile+'"}';

xhr.setRequestHeader("authorization", "Basic anBhdmFuOmpwYXZhbg==");
xhr.setRequestHeader("Content-Type", "application/json");       
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("cache-control", "no-cache");

xhr.send(data);
            };

Note: be careful with single quotes and double quotes. I messed up with these and took lot of time to fix it.

Comments