2

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?

3
  • 1
    Why not use jQuery.ajax? Commented Dec 7, 2018 at 5:12
  • And why not use jQuery for element creation. It's great for that: $('<div></div>').text(donHistory).appendTo(divElement) Commented Dec 7, 2018 at 5:17
  • @JonathanWilson Thanks. 1) I am new to this, will check out ajax. 2) JSON Link is just a placeholder for the purposes of this question. The actual code is a real link that returns real data that I don't want to show here. 3) The JSON data looks exactly like the example I gave above. 4) I will try that. Commented Dec 7, 2018 at 5:31

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

12 Comments

I tried using request.onload = function (data), but same result.
Add console.log(data) as the first line in onload. Then look that your JavaScript console. What do you see?
I changed the code in both places you suggested, and the log shows this: illiterategenius.net/console.png Status of 200.
OK. You should really switch from the low-level XMLHttpRequest to jQuery.ajax. You will have a much easier time.
Worked like a charm; thank you so much for sticking with this and helping me out.
|
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.