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
}
});
},