Giacomo Balli profile picture
Giacomo Balli
The Mobile Guy

Over two decades of experience at your service.
I help business owners make better decisions.

Let's Chat LinkedIn

Get all pages of paginated API Response

Get All Pages Of API

This code sample will allow you to iterate API calls when pagination is in place.

allResults=[];
currApiPage=1;
function getAllPages() {
	var url="http://google.com/API/search"+"?page="+currApiPage;
	var req = new XMLHttpRequest();
	req.open("GET",url,true);
	req.onload = function(evt){
		var resp=JSON.parse(evt.target.responseText);
		for (var i = 0; i < r.results.length; i++) {
            allResults.push(r.results[i]);
        }
        if (r.has_next) {
            currApiPage++;
            getAllPages();
        } else {
            currApiPage = 1;
        }
	}
	req.send(null);
}

Directions:
- replace http://google.com/API/search with your API url
- replace r.results with the array in your own JSON response
- usually when initializing your project, call getAllPages()

Note:
This snippet focuses on iOS development. Make sure to verify/adapt any vendor prefixes. Back to main listing.

Published: Sun, Jan 10 2016 @ 18:55:35
Back to Blog