Return Value from ClientContext.ExecuteQueryAsync in Javascript CSOM on SharePoint 2013

Sathish Nadarajan
SharePoint MVP
Published On :   16 Nov 2013
Visit Count
Today :  11    Total :   27744

Most of the time, we would have been came across to fetch the list items using Javascript CSOM object model using SP.JS. Whenever we want to do some action, we can very well do that on the Success method. But I faced a different scenario, where I need to return the fetched list item to the parent method which is calling from an iFrame. Hence, the remaining process needs to be done from the iFrame. Not from our javascript method. Let the picture speaks more about this.


With the above scenario, the code would be something like,

 function GetRating(sender, args) {
         var ctx = new SP.ClientContext(“http://sathishserver:20000/sites/VHS/”);
         var web = ctx.get_web();
         this.list = web.get_lists().getByTitle(ListName);
         this.listItems = list.getItemsByID(ItemID);
         ctx.load(listItems, 'Include(ID, AverageRating)');
         ctx.executeQueryAsync(Function.createDelegate(this, GetRatingSuccess), Function.createDelegate(this, GetRatingFailure));
 function GetRatingSuccess (sender, args) {
         RatingValue = listItems.itemAt(0).get_item("AverageRating");
     function GetRatingFailure (sender, args) {
         alert(‘GetRating():' + args.get_message());

Here, the GetRatingSuccess method is having the RatingValue. This value needs to be returned to the method within iFrame. I was trying with different options like Windows.Addlistener, attachevent, callback functions etc., but nothing had worked out. Since this is working with async thread, even the thread.sleep , settimeout, setinterval, nothing had worked out. At last, found an workaround. Instead of trying to return a value from this async function, call another method on the iFrame by passing this RatingValue as argument. This solves my requirement. J . The sample would be somewhat like

 function GetRatingSuccess (sender, args) {
         RatingValue = listItems.itemAt(0).get_item("AverageRating");

The “Success” is the method which will be available on the iFrame.

This is very simple right. But to arrive this, spent a lot of time digging into the Callback and eventlisteners for async method. But I could say that, it is a quality time. J .

Hope this helps. Thanks.

Happy coding.

Sathish Nadarajan.