I’d really love some advice on the best way to re-structure the below function. What I am doing is setting up the file reader and refreshing several divs content in a for loop. Basically, my code works perfectly as long as I leave in the bottom alert saying alert(sparespacetofill); for testing, but when I take this alert out, my div’s content do not get refreshed as should. Its obviously a problem with the reader.onload function not getting called before the function finishes running, but I really am stuck on how I should structure this differently.
function setup_reader(file,number, sparespacetofill) {
var name = file.name;
var reader = new FileReader();
reader.onload = function(e) {
$('#' + sparespacetofill).children('img').attr('src',e.target.result);
if ($('#' + sparespacetofill).find("p").length <= 0 && sparespacetofill !='pic0' ) {
$('#' + sparespacetofill).append('<p id="deleteit">Delete<a></p>');
}
}
reader.readAsDataURL(file);
//alert(sparespacetofill);///ISSUE IS IN HERE IF I UNCOMMENT THIS OUT
return sparespacetofill;
}
When the onload event fires, has the Ajax operation completely finished?
If so, whatever functionality you’re trying to perform when the function returns, instead perform it at the end of the onload function. Call a function there that continues on with whatever code you were running.
Reorganize the code as needed so it can be split into two parts: the part that runs before setup_reader() and that calls setup_reader(), and the part that runs after the onload event fires.