-2

My question is when I comment out "return maxID;" I got the result of an array of the IDs I have ( for example 1 2 3 4 5) but if I tried to return maxID, the result is 1 instead of 5. Why?? How to fix it? Here is my code:

     function storeData() {
    var maxID;

    var query = "SELECT 'ROWID', ID FROM " +
        'mytableID';
    var encodedQuery = encodeURIComponent(query);

    // Construct the URL
    var url = ['https://www.googleapis.com/fusiontables/v1/query'];
    url.push('?sql=' + encodedQuery);
    url.push('&key=myclientKey');
    url.push('&callback=?');

    // Send the JSONP request using jQuery
    $.ajax({
      url: url.join(''),
      dataType: 'jsonp',
      success: function (data) {
        var rows = data['rows'];
        var ftData = document.getElementById('ft-data');
        maxID = 0;
        for (var i in rows) {
          var rec = rows[i][0];
          var collection = rows [i][1];
          var idValue = parseInt (collection);
          if (idValue > maxID) 
             maxID = idValue;
          var dataElement = document.createElement('div');
          var recElement = document.createElement('p');
          recElement.innerHTML = rec;
          var collectionElement = document.createElement('p');
          collectionElement.innerHTML = collection;
          document.write(maxID);
          return maxID;
          });
          }
nlin
  • 3
  • 4

1 Answers1

0

The return comes too early, it's inside the loop, you leave success after the first row.

Basically the return is useless in a ajax-callback, simply print maxIDat the end of success.

Fixed $.ajax-call:

   // Send the JSONP request using jQuery
   $.ajax({
     url: url.join(''),
     dataType: 'jsonp',
     success: function(data) {
       var rows = data['rows'];
       maxID = 0;
       //don't use for-in-loops to iterate over arrays
       //for (var i in rows) {
       for (var i = 0; i < rows.length; ++i) {
         var rec = rows[i][0];
         var collection = rows[i][1];
         var idValue = parseInt(collection);
         if (idValue > maxID){maxID = idValue;}
          var dataElement = document.createElement('div');
          var recElement = document.createElement('p');
          recElement.innerHTML = rec;
          var collectionElement = document.createElement('p');
          collectionElement.innerHTML = collection;
        }
        //you shouldn't use write after the document has been loaded
        //document.write(maxID);
        document.body.innerHTML = maxID;
      }
    });
Dr.Molle
  • 116,463
  • 16
  • 195
  • 201