javascript - Array returning undefined at higher granularity -
i using ajax read csv file in object of arrays. problem i'm having data being read correctly , appears in object if move down layers undefined messages. though in top view of object there. think might have timing working large amounts of data.
js
$(document).ready(function () { var data = readcsv(); populatetable(data); }); function readcsv() { var data = {"columns":[], "rows":[]}; $.ajax({ url : 'assets/php/readcsv.php', type : 'post', success : function (csv) { var colcount = csv[0].length, rowcount = csv.length; (var c = 0; c < colcount; c++) { data['columns'][c] = csv[0][c]; } csv.splice(0,1); (var r = 0; r < rowcount; r++) { data['rows'][r] = csv[r]; } }, error : function () { alert("error: unable read csv file. please try again."); } }); return data; } function populatetable(data) { console.log(data); // outputs data expected. console.log(data['columns']); // shows columns data expected console.log(data['columns'][0]); // returns undefined }
snip-it of first console log
object { columns=[0], rows=[0]} columns ["experimnt code", "experimnt_name", "varcode", 12 more...] rows [["h1225", "cop - show star rating a...ting in price panel", "h1225:001.000", 12 more...], ["h1225", "cop - show star rating a...ting in price panel", "h1225:001.001", 12 more...], ["h1225", "cop - show star rating a...ting in price panel", "h1225:001.002", 12 more...], 4873 more...]
snip-it of second console log
[] 0 "experimnt code" 1 "experimnt_name" 2 "varcode" 3 "varname" 4 "version number" 5 "reporting range start date" 6 "reporting range end date" 7 "status" 8 "transaction date" 9 "experimnt test id" 10 "test manager" 11 "product manager" 12 "pod" 13 "record_update_datetm" 14 "insert_datetm"
third returns undefined though second snip-it can see data there.
whats going on?
the "a" in "ajax" stands "asynchronous". mean when make ajax request execution continues next line after $.ajax()
in readcsv()
function without waiting response. readcsv()
function returns before response , should returning {"columns":[], "rows":[]}
. later, when response received, success
callback executed, populatetable()
function has been invoked.
the explanation can think of why console logs showing of returned data in browsers console retain live link logged object. console shows object { columns=[0], rows=[0]}
because arrays empty @ time console.log(data)
ran (note zeros), , data['columns'][0]
undefined
@ moment. time click on object in console expand , see contents of arrays ajax response have been received , arrays have been populated.
the fix call populatetable()
within success
handler, because @ point data available.
Comments
Post a Comment