I'm setting a flag called flag_done, which I use to make sure there were no errors when updating my database records line by line. If there are no errors, I will reset the database.
The updating works fine, the flag_done variable shows 2 different values with 2 consecutive identical alerts.
What am I missing?
var flag_done = "initial";
function updateDatabase(){
  UpdateList = JSON.parse(localStorage["UpdateList"]);  // get it from local
  if (UpdateList.length > 0 ){
    for (i = 0; i < UpdateList.length; i++) {
      set_url = "checks/"+UpdateList[i].id+".json";
      $.ajax({
        type: "PUT",
        url: set_url,
        data: JSON.stringify(UpdateList[i]),
        contentType: 'application/json', // format of request payload
        dataType: 'json', // format of the response
        success: function(msg) {
          // flag_done = "success";  // this actually worked but the same issue as error, the initial value shows up first when alerting twice!
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          alert("OFFLINE!");
          flag_done = "error";  // This sets correctly
          alert("flag_done should be error: "+flag_done);  // Shows as error (correct)
        }
      } )
      alert("still inside for loop: "+flag_done);     // This shows initial and not error - ever!     
    }
    alert("flag_done: "+ flag_done); // shows initial
    alert("flag_done: "+ flag_done); // shows error!!
    if ( flag_done == "error" ) {
      alert("Couldn't SYNC right now, saved offline.");
    }else{
      alert("Updated OK");
      // resetDatabase();
    }
  } 
};
 
    