0

Ok basically i am trying to get some data from local to php mysql. Using LocalStorage and JavasScript. I use javascript to populate an array of values, stringify it with JSON.Stringify, then use the result as a parameter with a POST request to a PHP script. I use Chrome to preview my work. My code is as shown below:

function jsontest(){
  //debugger;
  var jsonData = [];
  //jsonData.push({"recordkey" : "syaf"})

  var objectStore = db.transaction("customers").objectStore("customers");
  objectStore.openCursor().onsuccess = function(event) {
      var cursor = event.target.result;
      if (cursor) {
        var v_key = cursor.key;
        var v_unit = cursor.value.unitno;
        var v_location = cursor.value.location;
        var v_item = cursor.value.item;
        var v_defect = cursor.value.defect;
        jsonData.push({"recordkey" : v_key})
        cursor.continue();
      }
      else {
        //alert("No more entries!");
      }
  };
  uploadJson(jsonData);
}

function uploadJson(jsonData){
  alert (jsonData);
  var jsonString = JSON.stringify(jsonData);
  alert (jsonString);
  var xmlHttp = new XMLHttpRequest();

  xmlHttp.open("POST", "upload_process.php", true);
  xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xmlHttp.send("x=" + jsonString); 
  xmlHttp.onreadystatechange = function(){
  if(xmlHttp.readyState == 4 && this.status == 200){
     var ajaxDisplay = document.getElementById('ajaxDiv');
        alert(xmlHttp.responseText);
        ajaxDisplay.innerHTML = xmlHttp.responseText;
    }
  }
}

So jsontest() composes the JSON string and passes the result into uploadJson, which will stringify the JSON data and send it as an AJAX request and display it in the webpage.

Here's the wierd part: It only works when i run it through Chrome's Developer Tools debugger. As in, the alerts(in uploadJson) show the correct values from the local storage and stringify. But if i do not use the debugger, somehow i don't get any value in jsonData. Can anyone help? I suspect its the Local Storage portion but I'm not sure what.

  • Your `.onsuccess` function is asynchronous, isn't it? You call `uploadJson(jsonData);` before the `.onsuccess` has been called. – nnnnnn Dec 11 '17 at 02:09
  • Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Sebastian Simon Dec 11 '17 at 02:11
  • @nnnnnn, how then do i know .oncussess is called? sorry, this is my first time dealing with asynchronous programming. i understand the concept of asynchronocity, where one process can happen seemingly at the same time but how does that concept apply to local storage functions? – roefffisher Dec 11 '17 at 08:05

0 Answers0