I am trying to write some code that updates a list item when a list edit form (EditForm.aspx) opens and closes.
I have written a function and assigned it to the onload and onbeforeunload events of the forms body element. The function gets a list item and then in the succeededCallback function of executeQueryAsync() it updates the item and calls executeQueryAsync() again.
When the form opens, the code runs without issue and the list item is updated, however when the form closes the function runs, but when it gets to executeQueryAsync(), neither succeededCallback or failedCallback functions are called and the list item is not updated.
Here is the code:
function updateItem() {
var clientContext = SP.ClientContext.get_current();
var web = clientContext.get_web();
var oList = web.get_lists().getByTitle('MyList');
var title = "TitleOfItemToUpdate";
var query = new SP.CamlQuery();
query.set_viewXml("<View><Query><Where><Contains><FieldRef Name='Title'/><Value Type='Text'>" + title + "</Value></Contains></Where></Query></View>");
var listItems = oList.getItems(query);
clientContext.load(listItems);
clientContext.executeQueryAsync(Function.createDelegate(this, onGotItems), Function.createDelegate(this, this.onQueryFailed));
function onGotItems() {
if (listItems.get_count() > 0) {
var itemToUpdate = listItems.itemAt(0);
var strVal = itemToUpdate.get_item('MyFieldVal');
// Do some other stuff with strVal
itemToUpdate.set_item('MyFieldVal', 'NewValue');
itemToUpdate.update();
clientContext.executeQueryAsync(Function.createDelegate(this, function () { alert("Item updated"); }), Function.createDelegate(this, this.onQueryFailed));
}
}
}
function onQueryFailed() {
alert("failed");
}
The code above is a simplification of the code that i am using. It works perfectly in body.onload, however in body.onbeforeunload it enters updateCreateAccessLog and when it gets to executeQueryAsync it just stops and doesn't call either the success or failure functions passed in as delegates.
Can anybody help me?
Many Thanks,
Toby