Use JSON received from server

Use JSON received from server
0

Hi,
In my code, I send a request to a server with

xhr.send(JSON.stringify({
        "Code":"SPTC2321326"
    }));
}

I then receive a reponse from the network with new informations
{Code: “SPTC2321326”, Name: “Bruno Mars”, Token: “randomNumbers”}
Now, I’m not sure how I can convert the JSON to an usable form in my html.
After some research, i saw that some people suggest to use JSON.parse, but their json data are always the same, while mine changes everytime.
What I think I’m supposed to do:

let response = '{"Code": "SPTC2321326", "Name": "Bruno Mars", "Token": "randomNumbers"}';

But I don’t know how to make it so that javascript takes the data returned by my request, since it changes everytime and I can’t write the value I get on one occasion. Sorry if I’m not completely clear.
Thanks you.

JSON.parse should do the trick. You can pass it different JSON each time and it will create a different JavaScript object in which you can extract the specific data you are trying to get.

How do I tell Javascript to take Code, Name and Token that I received and insert them in JSON.Parse with their random value?

I guess I might be misunderstanding what you are trying to do here. I thought you said you receive a response back in JSON format which you need to parse to get the values of the Code, Name and Token properties. Is that correct?

Let’s pretend the following is the JSON response I receive back:

{
  "Code": "SPTC2321326",
   "Name": "Bruno Mars",
   "Token": "randomNumbers"
}

I could parse this response like the following within the xhr.onload function.

const obj = JSON.parse(xhr.responseText);

Now obj is just a JavaScript object which you can reference the properties Code, Name, Token like you would in any other object.

console.log(obj.Name); // Bruno Mars

Thanks, that’s what I was searching for. I didn’t know responseText existed, is there a website which can help me with these?

Yes, the Free Code Camp curriculum.

https://www.freecodecamp.org/learn/data-visualization/json-apis-and-ajax/

Hi,
I’m trying to send a header which will authorize me to access data.

function authentificationToken(obj){
    console.log(obj);
    let xhr = new XMLHttpRequest();
    xhr.open('GET', 'http://website.com/messages');
    xhr.setRequestHeader("Authorization", "Basic obj");

    let chatText = JSON.parse(xhr.responseText)
}

The token is in obj, however, I don’t think I’m doing the authorization part correctly. My navigator doesn’t see my request, but my console line works.
Thanks you!

xhr.setRequestHeader("Authorization", "Basic obj");

The string “obj” is supposed to be a base-64 encoded representation of the credentials (user:password) so it should look something like

xhr.setRequestHeader("Authorization", "Basic YWxhZGRpbjpvcGVuc2VzYW1l");

If you need to send the whole object, I’m not sure. Maybe stringify it first and then base-64 encode it?

What does the object look like?

The object contain my token which changes every refresh, that’s why I used a variable for it, since it changes. If I can’t do that I don’t know what to use.

You probably just need to pull out the key(s)/value(s) out of obj that you are passing to the function, something like:

...
const {token} = obj; // if obj looks like this {token: the_token}
...
xhr.setRequestHeader("Authorization", "Basic whatever_you_get_when_base-64_encoding_token");
...

I’m not sure but I think I already have the value passed. This is what I get in Chrome from the console.log(obj):


I tried doing what you said but I’m doing it wrong I guess. Also, I don’t get any status code in the console.

Ah, okay then perhaps it’s ready-to-use:

xhr.setRequestHeader("Authorization", "Basic " + token);

Well thanks, it worked. My mistake was that I did not have xhr.send();.
Now today, I’m trying to take the elements I received and put them into my HTML. Here’s what I tried:

function writeChatMessage(chatMessage){
    console.log(chatMessage);
    for (i = 0; i <= 50; i++) {
        let chatSender = chatMessage[i].From;
        let chatMessDate = chatMessage[i].Date;
        let chatMessText = chatMessage[i].Text;
        let chatWindow = document.getElementById('chat');
        let ligne = chatWindow.createElement('DIV').outerHTML="<span class='chatDate'>"+chatMessDate+"</span>" +
            "<span class='chatUser'>"+chatSender+"</span>" +
            "<span class='chatMessage'>"+chatMessText+"</span>";

            ligne.className ="ligneChat";
    }

}

I think my issue is that I can’t use createElement like this in this situation, but basically I want to create a new div and include 3 inside of it with my data.
Thanks again!

You need to append that element as a child of an existing one.

I would change it up a little like this:

...
let chatWindow = document.getElementById('chat');
let ligneChat = document.createElement(...);
ligneChat.className = 'ligneChat';
chatWindow.appendChild(ligneChat);
...

You may need to append each inner element to ligneChat but maybe not. I usually don’t make elements using outerHTML like that.