1

I have been dealing with for the whole day. "sendResponse" is a callback function. Since I am dealing with ajax request, I have to use it to retreive the data after request. I just can't get it passed in side an anonymous function that handles the ajax response. What would be the solution here?

runningTimeEntry: function (sendResponse) {
      TogglButton.ajax('/time_entries/current', {
          method: 'GET',
          onLoad: function (xhr) {
              var responseData = JSON.parse(xhr.responseText);
              sendResponse(responseData.data); // this line doesn't work
          }
      });
  },

  ajax: function (url, opts) {
      var xhr = new XMLHttpRequest(),
          method = opts.method || 'GET',
          baseUrl = opts.baseUrl || TogglButton.$newApiUrl;
      xhr.open(method, baseUrl + url, true);
      if (opts.onLoad) {
          xhr.addEventListener('load', function () {
              opts.onLoad(xhr);
          });
      }
      if (TogglButton.$user) {
          xhr.setRequestHeader('Authorization', 'Basic ' + btoa(TogglButton.$user.api_token + ':api_token'));
      }
      xhr.send(JSON.stringify(opts.payload));
  },

In short, this returns {test:"test"}:

runningTimeEntry: function (sendResponse) {
  TogglButton.ajax('/time_entries/current', {
      method: 'GET',
      onLoad: 
          sendResponse({
              test: 'test'
          });         
  });
},

And this doesn't:

runningTimeEntry: function (sendResponse) {
  TogglButton.ajax('/time_entries/current', {
      method: 'GET',
      onLoad: function (xhr) {
          sendResponse({
              test: 'test'
          }); // this line doesn't work
      }
  });
},
Eris
  • 11
  • 3
  • Could you please indent your code properly? Put it into http://jsbeautifier.org/ and [edit] your question – Bergi Jul 10 '14 at 18:38
  • 1
    You're wrong. `sendResponse` *stays* in scope, that's what closures are made for. If you're getting an exception there, the mistake must be somewhere else. – Bergi Jul 10 '14 at 18:39
  • What is the error you are getting? Please be specific about what is going wrong. – forgivenson Jul 10 '14 at 18:47
  • in the first case, you are calling `sendResponse` immediately, instead of assigning it to `onLoad`. As for the second case, there is likely something else going wrong that isn't in this javascript. – forgivenson Jul 10 '14 at 18:57
  • This is my first time modifying a chrome extension. So first problem was, that the background.js script is not reporting errors to the page console, but to the special screen. The second problem was, that there were no errors at all. After extensive digging this turned out to be the answer: http://stackoverflow.com/questions/20077487/chrome-extension-message-passing-between-extensionbackground-and-content-scrip Async in javascript. Thank you for the help. – Eris Jul 10 '14 at 22:34

0 Answers0