Search code examples
javascriptnode.jsajaxgoogle-chrome-extensionget

Update data using Javascript ajax async failed


I am using HTML, javascript and Nodejs code to develop chrome extension. On page load, I am calling the function getBalance() to get data and bind it to the HTML span. Following is my code:

function getBalance() {
    var request = new XMLHttpRequest();
    request.open('GET', 'http://xxx.xxx.xx.xxx:xxxx/getAccount?address=xxxxxxxxxxxxxxxxxxxx', true);
    request.onload = function () {
      var data = JSON.parse(this.response);
      if (request.status >= 200 && request.status < 400) {
        var bal = data.Balance;
        var etherprice = bal / 1000000000000000000;
        document.getElementById("accbal").innerHTML = etherprice;
      } else {
        console.log('error');
      }
    }
    request.send(null);
}

window.addEventListener('load', function load(event){
    getBalance();
});

function sendTransactionBroadcast(result){ 
    var doAjax = function() { 
    $.ajax({ 
    type : "POST", 
    url : "http://xxx.xxx.xx.xxx:xxxx/broadcast",   
    data: JSON.stringify(result), 
    contentType: 'text/plain; charset=UTF-8', 
    success:function(json){ 
      console.log(json);
      getBalance();
    }, 
    error: function() { 
    alert("Error"); 
    } 
    }); 
    } 
    doAjax(); 
    }

sendTransactionBroadcast() function is called on button click, this function is having ajax async POST call. After its execution complete, On success, I want updated data from getBalance() function and bind it to the span. So, I am calling it again on ajax success. Problem is, if I set debugger and debug the code line by line, I get the updated data in span innerHTML. Everything goes fine. But, if I close debugger, and click the button the span innerHTML is not getting changed on UI. I am not getting the reason why? Also sometimes it changed sometimes not. Is this ajax async response issue or something else? How to solve this?

manifest.json

{
  "manifest_version": 2,

  "name": "C Wallet",
  "description": "The C Wallet in your browser",
  "version": "1.0",

  "browser_action": {
   "default_icon": "Image/CI_logo-01.png",
   "default_popup": "popup.html"
  },
  "icons": { "16": "Image/CI_logo-01.png",
    "48": "Image/CI_logo-01.png",
   "128": "Image/CI_logo-01.png" 
  },
  "permissions": [
   "activeTab"
   ]
}

Solution

  • Well, I found the problem. As I was using HTML button type="submit" which was the reason that the page was getting load and the data was not getting changed according to what I was setting. It was getting reset. To avoid page load I used button type="button" and all problems got solved.