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

Sathish Nadarajan
 
Solution Architect
November 16, 2013
 
Rate this article
 
Views
42560

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.

image

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");
         
 document.getElementById("iFrameID").contentWindow.Success(RatingValue);
 
     }
 

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.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Leave a comment