2

I'm trying to save some data to localStorage on my offline application. When user on offline mode, then browser will collect data from form, FormData object, store it to localStorage and when browser is online then it will push the FormData object that store in localStorage to server via jQuery ajax. The complexity is that the form have dynamic fields and can have the fileupload field and the problem is that the localStorage on html5 support data as string and not the object.

Collection.prototype.storeOfflineData = function(collectionId){
   var formData = new FormData($('form')[0]);
   pendingSites = {"collectionId" : collectionId, "formData" : formData};
   window.localStorage.setItem("offlineSites", JSON.stringify(pendingSites));
   Collection.prototype.goHome();
   Collection.prototype.showErrorMessage("Successfully store data in offline.");
}

When the browser is online,connected to internet, I created the methods to read FormData from local storage and make ajax request to server but ajax request got error because the JSON.parse return "[object object]"

Collection.prototype.pushingPendingSites = function(){
  pendingSites = JSON.parse(window.localStorage.getItem("offlineSites"));
  if(pendingSites != null){
    console.log(pendingSites[i]["formData"]);
    Collection.prototype.ajaxCreateSite(pendingSites[i]["collectionId"], pendingSites[i]["formData"]);
  }
}

Collection.prototype.ajaxCreateSite = function(collectionId, formData){
  $.ajax({
    url: '/mobile/collections/' + collectionId + '/sites',  //Server script to process data
    type: 'POST',
    success: function(){
      Collection.prototype.goHome();
      Collection.prototype.showErrorMessage("Successfully saved.");
    },
    error: function(data){
      Collection.prototype.showErrorMessage("Save new site failed!");
    },
    data: formData,
    cache: false,
    contentType: false,
    processData: false
  });
}
11
  • It works fine for me, may be the FormData object is not as per the JSON standards, can you provide what is the output for formData, just do console.log(formData) Jan 13, 2014 at 3:24
  • Is there a reason you're using a FormData object instead of just storing the values of the form fields?
    – Musa
    Jan 13, 2014 at 3:27
  • FormData { append=append()} but after stringify and use JSON.parse it return Object {}. I think Stringify may change the FormData object. Jan 14, 2014 at 2:27
  • @Musa my form is dynamic forms. So i need a FormData object to get all the data in the form and send to server via jquery ajax. Jan 14, 2014 at 2:29
  • Take a look at api.jquery.com/serializearray
    – Musa
    Jan 14, 2014 at 3:01

0

Your Answer

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

Browse other questions tagged or ask your own question.