-1

Since I loaded a project to the web server I am getting this error message after the first refresh:

TypeError: oModel.responseJSON is undefined

Although the variable exists and AJAX succeed. The error refers to this line:

<body onload="displayEntries(oModel.responseJSON.results);">

I load before the body close tag the following JS:

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="js/user.js"></script>

JS runs in strict mode and in the "user.js" I have this code:

    let oModel = $.ajax({
        url: 'data.php',
        dataType: 'json'
    }); 
function displayEntries(entries) {
    $("#div").empty();
    let html = "";

    jQuery.each(entries, function(i, entry) {
        html = '<div id="cid-' + i + '" class="entry">' + entry.name + '</div>';
        $("#div").append(txt);
    });
}

When I enter "oModel.responseJSON.results" into the console, it is displayed correctly.

Migster
  • 141
  • 9
  • 1
    You don't have a "success" callback set up for your AJAX operation and are trying to access it before it is available. – Scott Marcus May 25 '18 at 20:23

2 Answers2

2

Ajax is asynchronous

Get rid of onload="displayEntries and just call the function in succcess callback of $.ajax

$.ajax({
    url: 'data.php',
    dataType: 'json'
}).then(displayEntries); 
charlietfl
  • 164,229
  • 13
  • 110
  • 143
1

This happens because you're trying to access value of a variable before the AJAX call is over.

Call the displayEntries() function after the AJAX call is over like so:

$.ajax({
  url: 'data.php',
  dataType: 'json'
}).done(function(data) {
  displayEntries(data)
});
user3210641
  • 1,427
  • 9
  • 13