Yakimget
Yakimget

Reputation: 35

Cannot get data from HTTP GET - Javascript

I'm using SpringBoot. In '/api/events' I have a list of events. Here's Java code that returns that list:

@GetMapping(path = "/api/events", produces = "application/json")
@Transactional
public @ResponseBody List<?> getEvents() {
    Query q = entityManager
            .createQuery("SELECT DISTINCT e FROM Event e JOIN e.blocks b WHERE b.begin > :currDate")
            .setParameter("currDate", new Date());
    return q.getResultList();
}

How data in /api/events looks like:

[
  {"eventId":1,"title":"Test Event","owner":{"nick":"asd","mail":"[email protected]","userId":5},"blocks":[{"blockId":1,"begin":"2018-01-01T11:00:00.000+0000","end":"2018-01-01T14:00:00.000+0000","minPerSlot":10},{"blockId":2,"begin":"2018-08-01T10:00:00.000+0000","end":"2018-08-01T13:00:00.000+0000","minPerSlot":10}]},
  {"eventId":3,"title":"Test2","owner":{"nick":"asd","mail":"[email protected]","userId":5},"blocks":[{"blockId":3,"begin":"2018-08-01T10:00:00.000+0000","end":"2018-08-01T13:00:00.000+0000","minPerSlot":10}]}
]

In JS I want to load that data. I'm using this code:

function loadEvents() {
  var events = httpGet("/api/events");
  var len = events.length;
}

var getJSON = function(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.responseType = 'json';
  xhr.onload = function() {
    var status = xhr.status;
    if (status === 200) {
        callback(null, xhr.response);
    } else {
        callback(status, xhr.response);
    }
  };
  xhr.send();
};

function httpGet(theUrl) {
  getJSON(theUrl,
    function(err, data) {
        if (err !== null) {
            alert('Something went wrong: ' + err);
        } else {
            return data;
        }
    });
}

Then I receive an error: Uncaught TypeError: Cannot read property 'length' of undefined at loadEvents That what I get, isn't an array of JSON objects? How should I parse it?

Upvotes: 0

Views: 102

Answers (1)

JacobS
JacobS

Reputation: 606

httpGet isn't actually returning anything to the caller. If you want to use the callback pattern you would want to do something similar to this:

function loadEvents() {
  var events = getJSON("/api/events", function(err, events) {
    if (err) throw Error(err); // error handle here
    // logic here
    var len = events.length;
  });
}

var getJSON = function(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.responseType = 'json';
  xhr.onload = function() {
    var status = xhr.status;
    if (status === 200) {
        callback(null, xhr.response);
    } else {
        callback(status, xhr.response);
    }
  };
  xhr.send();
};

Upvotes: 1

Related Questions