0

I am so so stuck with this. I have a functionA which I want to call functionB (my API call) and have it return the results of the data. The API is a "queue" and "get" type. It should run like this:

  1. Run API query with "queue" type
  2. Collect returned reportID
  3. Run API query with "get" type and reportID
  4. Collect data into myfunction

This is my current code:

function myfunction() {
  var ref;
  var type = "queue";
  var metric = "pageviews";
  var post = getReport(ref, type, metric);
    post.done(function (r) {
        console.log (r);
        }
    );
}

function getReport(ref, type, metric) {
   return $.ajax({
        url: "report.php", 
        dataType: 'json',
        data: { 
            ref: ref,
            type: type, 
            metric: metric
        }
    });
}

This works fine. However I can't get the loop working correctly for the second part of my query. This is what I tried:

function myfunction() {
  var ref;
  var type = "queue";
  var metric = "pageviews";
  var post = getReport(ref, type, metric);
    post.done(function (r) {
        if (type == "queue")
        {
        myfunction(r.reportID,"get");
        }
        else if (type == "get")
        {
        console.log(r);
        }
    );
}

I keep overwriting the value of type which seems to cause an infinite loop.

9
  • 1
    where do you change the value of type from queue to get Commented Oct 9, 2018 at 10:13
  • Also, you need to add arguments to your function. Commented Oct 9, 2018 at 10:14
  • @ThoVu when I call the function myfunction(r.reportID,"get"); Commented Oct 9, 2018 at 10:16
  • But even if I put this back into the function it still gets overwritten. Commented Oct 9, 2018 at 10:17
  • You are trying to solve a problem that shouldn't exist in the first place. Why do you want to have that recursive myfunction call in there? And when you do myfunction(r.reportID,"get"); the "get" is simply ignored completely. Not only has myfunciton no arguments, even if it did, you're shadowing type by hardcoding it to "queue"- Commented Oct 9, 2018 at 10:18

1 Answer 1

1

Here's a basic solution that chains (actually: nests) the API calls:

function myfunction(ref) {
  getReport(ref, "queue", "pageviews").done(function(r1) {
    getReport(r1.reportID, "get", null).done(function(r2) {
      console.log(r2);
    })
  });
}

function getReport(ref, type, metric) {
  return $.getJSON("report.php", {
    ref: ref,
    type: type,
    metric: metric
  });
}

(I'm guessing how your API works / what it returns but it should be easy enough to fit)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Chris, that's great

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.