jmease
jmease

Reputation: 2535

Javascript Call Synchronous Function From External JS File

I have a function in a .js file that takes information stored in localStorage and syncs them back to the server using synchronous ajax calls. (Order of integration is vital, hence synchronous is necessary)

function syncUp() {
    var xml = new XMLHttpRequest();
    xml.open("GET", "Default.aspx", true);  Also tried setting this to false
    xml.onreadystatechange = function() {
       if (xml.readyState == 4) {
         if (xml.status == 200) {
             var items = localStorage.getItem("SyncOrder");
             var sync = items.split(",");

             for (var i = 0; i < sync.length -1; i++) {
                 Perform repeated synchronous calls to webservice via AJAX to integrate each item to the server
              }
           }
        }
     }
  xml.send(null);
  }

syncUp() is being called from more than one place. When called directly from the onclick event of a button where syncUp() is the only function called and the only code running, it works great. However, if from a page where I am first adding an item to the localStorage object and then calling syncUp() as follows

function saveEdit(item) {
      var currData = localStorage.getItem("SyncOrder");
      localStorage["SyncOrder"] = currData + "," + item;
      syncUp();
}

, the xmlHTTPRequest status returns 0 and the sync doesn't perform. What could possibly be preventing the xmlHTTPRequest from getting a response of 200 as the only code running before syncUp() is a couple lines of javascript, which should be done executing before the site even gets into syncUp()?

Upvotes: 1

Views: 448

Answers (1)

epascarello
epascarello

Reputation: 207527

There are two causes of status code of zero.

  1. Making calls from the file protocol.
  2. The page is refreshing/navigating away as the request is being made.

In your case I would assume it is #2. If you are using a button or a link to make the Ajax call, make sure to cancel the click action with either preventDefault or return false.

Upvotes: 1

Related Questions