Search code examples
javascripthtmlxmlhttprequest

How to select specific Variables retrieved using XMLHttpRequest


I am trying to to an integration on my website. I have successfully retrieved data using XMLHttpRequest, However I don't need all the information I only need specific information.

This is my JavaScript code
`

Using the XMLHttpRequest Object

 <div id="demo">
 <button type="button" onclick="loadXMLDoc()">Change Content</button>
 </div>

 <script>

 function loadXMLDoc() {
 var url = "https://api.paystack.co/transaction/";

 var xhr = new XMLHttpRequest();
 xhr.onreadystatechange = function() {
 if (xhr.readyState == 4 ) {
  document.getElementById("demo").innerHTML =
  xhr.responseText;
  console.log(xhr.responseText);
   
 }
};

 xhr.open("GET", url);

  xhr.setRequestHeader("Authorization", "Bearer secret key");

 xhr.send();

}
 </script>

`

This is the response on the console, not all of it just showing the some part

{ 
"status": true, 
"message": "Transactions retrieved", 
"data": [ 
    { 
        "id": 1806822806, 
        "domain": "test", 
        "status": "abandoned", 
        "reference": "773768164", 
        "amount": 56050, 
        "message": null, 
        "gateway_response": "The transaction was not completed", 
        "paid_at": null, 
        "created_at": "2022-05-09T12:17:25.000Z", 
        "channel": "card", 
        "currency": "NGN", 
        "ip_address": "197.210.55.168", 
        "metadata": 
            { 
                "customer": 
                    { 
                        "id": 79455936, 
                        "first_name": "", 
                        "last_name": "", 
                        "email": "sdfeferw@lkkil.com", 
                        "phone": "", 
                        "metadata": null, 
                        "customer_code": "CUS_xxxxxx", 
                        "risk_action": "default" 
                    }, 
                    
                        
            },

The information's I need are the

  1. The creation date
  2. First Name
  3. Last Name
  4. Amount

I want to display them on a DIV, Please how do I do it


Solution

  • xhr.responseText is a JSON string. You need to prase it into a JS object and select only needed properties. Like

    const jsonResponse = JSON.parse(xhr.responseText);
    const { metadata, amount, created_at } = jsonResponse.data;
    const { first_name, last_name } = metadata.customer;
    const result = { first_name, last_name, created_at, amount };
    document.getElementById("demo").innerHTML = JSON.stringify(result);