Aryan Aryan - 4 months ago 8x
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);

var client = new XMLHttpRequest();"POST","");
window.location = 'activate';

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


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) {

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");


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