I'm currently facing a major roadblock when it comes to resolving my issues with callbacks. I've gone through resources like How to return value from an asynchronous callback function? and How to return the response from an Ajax call?, among several others. While the latter was helpful for a different problem, I find myself struggling to adapt it to my current situation. It's possible that my approach is fundamentally flawed rather than just being inexperienced, which can be quite frustrating.
The core of my issue lies in the fact that I need the JSON result not only returned to a single callback function but also accessible by various functions corresponding to different events. For example:
Clicking on linkOne should trigger ajaxReq + getJsonData, followed by calling functionOne with the result as an argument
Clicking on linkTwo should also do the same with functionTwo
And clicking on linkThree should work similarly with functionThree
Can't we achieve this using link.onclick definition? Why does something like this not work:
linkThree.onclick = functionOne(getJsonData);
Below is an excerpt of my code:
function ajaxReq() {
var request = new XMLHttpRequest();
return request;
}
function getJsonData() {
var request = ajaxReq();
// Code omitted for brevity
return myJsonArray; // This is where I'm facing issues
}
function functionOne(myJsonArray) {
var myJsonArray = getJsonData();
// The above line doesn't work as expected
}
If invoking `ajaxReq()` inside `getJsonData()` returns the desired result, why doesn't the similar invocation in `functionOne` yield the same outcome?
Any assistance on how to tackle this would be highly appreciated. (Note: Preferably looking for a solution in pure JavaScript without relying on jQuery.)
svs