jquery length error when trying to find json file through Ajax within .Net core

0

I have been receiving this error within jquery:

Unhandled exception at line 422, column 4 in http://localhost:59307/lib/jquery/dist/jquery.js
0x800a138f - JavaScript runtime error: Unable to get property 'length' of undefined or null reference occurred

This is displayed within this jquery method:

grep: function( elems, callback, invert ) {
    var callbackInverse,
        matches = [],
        i = 0,
        length = elems.length,
        callbackExpect = !invert;

    // Go through the array, only saving the items
    // that pass the validator function
    for ( ; i < length; i++ ) {
        callbackInverse = !callback( elems[ i ], i );
        if ( callbackInverse !== callbackExpect ) {
            matches.push( elems[ i ] );
        }
    }

    return matches;
},

Specifically the line:

length = elems.length

This is being caused by this Ajax statement which is trying to find a json file that is within a json folder on wwwroot:

function GetBucklingData() {
   var returnData;
   $.ajax({
       url: "/json/BucklingData.json",
       async: false
   }).done(function (data) {
       returnData = JSON.parse(data);
   });

   return returnData;
}

Here is an example grep statement from within a function:

 var rods = $.grep(bucklingData, function (s) {
      return (s.Bore == boreValue);
 });

The statement is called like this:

var bucklingData = GetBucklingData();
PopulateBoreDropdown(bucklingData);

It seems that ajax isnt able to find the json file. The code is working outside of .net with a simple html page and a standalone folder so the json file appears to be fine.

Any ideas?

javascript
jquery
.net
ajax
asked on Stack Overflow Oct 13, 2017 by HazardAGuess • edited Oct 13, 2017 by HazardAGuess

1 Answer

0

instead of using your function like this:

function GetBucklingData() {
   var returnData;
   $.ajax({
       url: "/json/BucklingData.json",
       async: false
   }).done(function (data) {
       returnData = JSON.parse(data);
   });

   return returnData;
}

var data = GetBucklingData();

change to an async logic:

function GetBucklingData(callback) {
   var returnData;
   $.ajax({
       url: "/json/BucklingData.json",
       async: false
   }).done(function (data) {
       callback(JSON.parse(data));
   });
}


GetBucklingData(function(data) {
  // here you have your data
  console.log(data);
});
answered on Stack Overflow Oct 13, 2017 by Apolo

User contributions licensed under CC BY-SA 3.0