0

I am having an issue while saving an item(editform.aspx) using below PreSaveAction function. I am using JSOM to fetch some information from SharePoint 2010 list and I expect it to return true or false on success or fail function. Since Async function runs ahead of time before any value is returned it doesnt save the item. Any solution on handling it?

function PreSaveAction() {
    var context = new SP.ClientContext.get_current();
    var web = context.get_web();
    var targetList = web.get_lists().getByTitle('Reviews');
    var query = new SP.CamlQuery();
    var caml = My caml query;
    query.set_viewXml(caml);
    var listItems = targetList.getItems(query);
    results = context.loadQuery(listItems);
    var callback = context.executeQueryAsync(_onSucceed, _onFail);
    alert(callback); //returns undefined
    return callback;
}

function _onSucceed() {
    alert("Success");
    return true;
}

function _onFail() {
    alert('failed reading data');
    return false;
}

2 Answers 2

0

The only solution is to not just handle the PreSaveAction but the whole saving process yourself. So instead of letting PreSaveAction return true you should directly trigger the function that saves the item once the successHandler is reached. Inspecting the Save-button with your Dev Tools should give you an idea how to call that function directly.

0
1

Below code worked for me. I had added custom function that triggers on Save button click and later used the inbuilt save functionality to save the item.

var originalSaveButtonClickHandler = function(){
};

$(document).ready( function () {
  var saveButton = $("[name$='diidIOSaveItem']");
 if (saveButton.length > 0) {
    originalSaveButtonClickHandler = saveButton[0].onclick;  
  }

  $(saveButton).attr("onClick", "ValidateForm()"); 

});

function ValidateForm() 
    {   
          var itemId = GetUrlKeyValue('ID');
          var context = new SP.ClientContext.get_current();
          var web = context.get_web();
          var targetList = web.get_lists().getByTitle('Reviews');
          var query= new SP.CamlQuery();
          var caml = CAML QUERY;
          query.set_viewXml(caml);
          var listItems = targetList.getItems(query); 
          results = context.loadQuery(listItems);
          context.executeQueryAsync(_OnSuccess, _OnFail);
    }

function _OnSuccess() {
alert("Success");
//Calling the save default save function
 originalSaveButtonClickHandler();   

}

 function _OnFail() {
          alert("Failure.");
    }

Here is another thread for reference. Wait async query in PreSaveAction

1
  • For some reason, this is not working on new forms in FireFox and IE. Any ideas?
    – Perneel
    Commented Nov 27, 2018 at 16:51

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.