1

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()?

1
  • Button onclick event. Saves the edits made to that particular page in localStorage then tries to sync it. Commented Nov 10, 2011 at 17:06

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Well now I just feel foolish. Forgot to remove the location = location line I had in there to refresh the page from when I had all this structured differently. Removed that and now all is fine. Thanks so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.