Reputation: 1122
I have a site which I built an infinite scroll for and as you scroll it loads the next X results, but I was wondering if theres a standard or better / prefered way of signaling you have come to the end and not to do any more requests.
At the moment it justs 404s when requesting data thats after the "end" of the data. If AJAX call receives an error/the 404 in response then it will remember not to make a call anymore.
But to me it feels a bit raw and was wondering whats the usual (if any) way of dealing with this is.
Upvotes: 1
Views: 1064
Reputation: 144912
If we assume that your "get results" API call looks something like this:
$.get('/results', { start: n }, function() ...); // for ex, /results?start=0
And returns something like:
[{ name: 'Result 1' }, { name: 'Result 2' }, ... ]
Where n
is the number of results already loaded, then it doesn't really make sense semantically to return a 404 error, which means the requested resource (which is /results
) does not exist. This is not true; /results
does exist, but the request parameters result in no data.
It is more appropriate to return a 200 with an empty array,
[]
...or respond with HTTP 204 No Content, which means that the request was successful, but there is nothing to return. This does save a few bytes since the server needn't send Content-Type
or Content-Length
headers and a response body.
(I'd use the 204.)
Either way, your client-side script knows that a 204 or an array of length 0 means that there's no more data, and can stop making requests.
Upvotes: 1
Reputation: 141829
If you Ajax is returning HTML or text, then just return an empty response to signify that there is no more data.
If the Ajax is returning JSON, then you can just add "status" property to the object representation.
Either way you should probably respond with HTTP 200, not 404.
Upvotes: 1
Reputation: 19203
How are you handling paging? Often it is recommended to include a "next page" link in your AJAX response. If you do so it avoids having to do math on the client, and provides an easy communication mechanism, just don't include the link if it would not be valid.
Upvotes: 1