2

I am learning AJAX.

I am using vanilla JS

I want to put a limit on the data received through an API eg: 10 objects max.

here is the url:- https://jsonplaceholder.typicode.com/photos

The problem is that when I create a GET request then the data which is fetched is huge approx 5000 objects. I want to use limited data so how I go about that.

this is the javaScript code:

const next = document.getElementsByTagName("button"),
     body = document.querySelector("body");


body.addEventListener("DOMContentLoaded",runEvents);

function runEvents(){
   nextBtn();
}

function nextBtn(){
   //set up the XMLHTTPObject ajax object
   const xhr = new XMLHttpRequest();

   xhr.open("GET", "https://jsonplaceholder.typicode.com/photos", true);

   xhr.onprogress = function(){
       document.getElementsByTagName("img").setAttribute("src", "img/loading.gif");
   };

   xhr.onload = function(){
       if(this.status === 200){
            document.getElementsByTagName("p").textContent = "Data Found"
           //I want to use the data recieved here

           
       }else{
           document.getElementsByTagName("img").style.display = "none";
           document.getElementsByTagName("p").textContent = "Data not found";
           
       }
   };
   
  

}
2

3 Answers 3

4

Adding my comment as an answer.

Limiting often depends on what the server supports.

Check whether the api request has a limit or a paging parameter: in your case try https://jsonplaceholder.typicode.com/photos?_start=0&_limit=5

(from https://github.com/typicode/jsonplaceholder/issues/65) –

3

depends entirely on the server, you can not limit server response via js. see mrblewog answer and just use jsonplaceholder.typicode.com/photos?_start=0&_limit=5 jsonplaceholder limit query parameter

1
  • Adds nothing beyond copying my comment.
    – user3456014
    Commented Jun 27, 2020 at 12:03
0

to limit the api response until 6 posts https://jsonplaceholder.typicode.com/posts?_limit=6"

Not the answer you're looking for? Browse other questions tagged or ask your own question.