Eellitterruht Jeenyes
Eellitterruht Jeenyes

Reputation: 25

JSON Data not Displaying on Webpage

I am trying - for the first time - to connect to a Blackbaud API, retrieve a JSON object, and display it on a web page. The request.open link I am using (not shown below because it contains user data) returns information with no error when I put it directly into browser.

An example of the JSON data return is here:

{"getConsTransactionsResponse":{"transaction":{"amount":{"formatted":"$50.00","decimal":"50.00"},"timestamp":"2016-02-01T09:43:54.458-06:00","pay_method":"ONLINE","billing_name":{"title":null,"last":"Smith","suffix":null,"middle":null,"first":"John","prof_suffix":null},"transaction_type":"DONATION","tender_type":"INVALID","confirmation_code":{},"donation_detail":{"value_of_goods":{"formatted":"$0.00","decimal":"0.00"},"tax_deductible_amount":{"formatted":"$0.00","decimal":"0.00"},"level":{"id":"9921","title":"API Donation Level"},"form":{"id":"9999","title":"API Form","description":"Sample form for API documentation."},"campaign":{"id":"9901","title":"API Campaign","description":"Sample campaign for API documentation."}},"billing_address":{"street2":null,"zip":null,"street1":null,"county":null,"state":null,"street3":null,"country":null,"city":null}}}}

The script I am using to retrieve and then display the data is here:

<script type="text/javascript">
$(document).ready(function() {
    "use strict";

    var donHistory = "";
    var request = new XMLHttpRequest();
    request.open('GET', 'JSON LINK', true);
    request.onload = function () {
        // begin accessing JSON data here
        var data = JSON.parse(this.response);
        donHistory += '<div>';
        for (var i=0; i<data.length; i++) {
            donHistory += data[i].transaction.amount + '<br>';
        }
        donHistory += '</div>';         
        var divHistory = document.createElement("div");
        var divHistoryText = document.createTextNode(donHistory); 
        divHistory.appendChild(divHistoryText);
        var divElement = document.getElementById("col-content-box");
        divElement.appendChild(divHistory);
    };      
    request.send();
});

What gets displayed on my web page is just an opening and closing div.

It's placed in the right area, just with no JSON data. The console shows no errors. Obviously, I am new to this and am making some simple mistake.

What I would like help with is:

1) Why isn't the JSON data which I know exists not making its way to the screen?

2) If/when I do get this working, what am I doing wrong to make the display as text instead of embedded as code?

Upvotes: 2

Views: 1956

Answers (2)

Jonathan Wilson
Jonathan Wilson

Reputation: 4295

Please see the following snippet, which resembles the code in your most recent screenshot. You should be able to run the snippet right here on this site to see that it works. I've changed a few things around:

  • I de-coupled the AJAX call from the code that generates HTML for display using renderTransactions
  • I used renderTransactions to display some of my own test data, for demonstration purposes
  • I wrote renderTransactions to use a ES2015 feature called Template Literals that allowed me to merge data values with HTML succinctly
  • I rendered your data to a table (styled with bootstrap). My choice of a <table> is arbitrary; you could use any HTML elements you want.

Hopefully you can see how to extend what I've started here for your application. There's a comment in the snippet describing how you'd re-hook-up your AJAX call, which I have disabled for demonstration purposes.

Good luck!

$(document).ready(function() {

  /* Since I do not have access to your HTTP endpoint, 
   ** I've used my own test data that resembles your data.
   ** When you're ready to run this code against your endpoint,
   ** remove the block up to and including the `return` statement.
   */

  renderTransactions([
    {amount: {formatted: '$1.00'},credit_card_type: 'VISA'},
    {amount: {formatted: '$2.00'},credit_card_type: 'MASTERCARD'},
    {amount: {formatted: '$3.00'},credit_card_type: 'MASTERCARD'},
    {amount: {formatted: '$4.00'},credit_card_type: 'MASTERCARD'},
    {amount: {formatted: '$5.00'},credit_card_type: 'VISA'}
  ]);

  return;

  $.ajax({
    dataType: 'json',
    url: 'INSERT YOUR URL HERE',
    method: 'GET',
    /* I think this should be GET but in your screenshot it appeared that you had something much longer here, not sure why. */
    success: function(data) {
      renderTransactions(data.getConsTransactionsResponse.transaction);
    }
  });
});

function renderTransactions(transactions) {
  let $transactionTable = $(`
    <table class="table table-bordered table-sm">
      <thead>
        <tr>
          <th>Amount</th>
          <th>Credit Card Type</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>`).appendTo('#col-content-box');

  let $transactionTableBody = $transactionTable.find('tbody');

  transactions.forEach(t => {
    $transactionTableBody.append($(`
      <tr>
        <td>${t.amount.formatted}</td>
        <td>${t.credit_card_type}</td>
      </tr>
    `));
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<div id="col-content-box"></div>

Upvotes: 1

Shahrukh Ahmad
Shahrukh Ahmad

Reputation: 153

Check console (pressing F12) you might see an error "response undefined" . If this is true, then you have to put 'response' variable on 'onload' function, like this :

request.onload = function (response) {

Upvotes: 1

Related Questions