title: Modifying response using server side scripts on Azure Mobile Services
body: <p>I have a mobile app for which I am using Azure Mobile Services as a backend.  I have a scenario in which I need to modify the elements that the client is requesting from the database.  I need to compute the rank and percentile of the record being requested, based on its best score and the best scores of all other records in the table.  I followed the <a href="http://msdn.microsoft.com/en-us/library/windowsazure/jj631631.aspx" rel="nofollow">example here</a> and wrote the below script:</p>
  
  <pre><code>function read(query, user, request) {
      request.execute({
          success: function(results) {
              results.forEach(function(item) {
                  var totalsql = "SELECT COUNT(*) FROM scoreInfo";
                  mssql.query(totalsql, {
                      success: function(totalresults) {
                          var totalCount = totalresults[0].Column0;
  
                          var moresql = "SELECT COUNT(*) FROM scoreInfo WHERE bestscore &gt; ?";      
                          mssql.query(moresql, [item.bestscore], {
                              success: function(moreresults) {
                                  var moreBestCount = moreresults[0].Column0;
  
                                  item.bestrank = moreBestCount + 1;
                                  item.bestpercentile = 100 - moreBestCount*100/(totalCount+1);                                
                              }
                          });
                      }
                  });
              });
              request.respond();
          }
      });
  }
  </code></pre>
  
  <p>But I don't see the results as expected on the client side.  I even tried logging the results on the server side but what I see on the client side doesn't match what is logged.  What am I doing wrong?</p>