Tips for restricting the information retrieved from an API?

Currently, I am in the process of learning how to use AJAX with vanilla JS. My goal is to implement a limit on the amount of data received from an API, specifically restricting it to 10 objects maximum.

The API url that I am working with can be found here: https://jsonplaceholder.typicode.com/photos

However, I have encountered an issue where the GET request fetches a large amount of data, approximately 5000 objects, which is much more than I need. I am looking for a solution to filter and work with only a limited amount of data.

Below is a snippet of the JavaScript code I am using:

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


body.addEventListener("DOMContentLoaded",runEvents);

function runEvents(){
   nextBtn();
}

function nextBtn(){
   //setting 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 would like to handle the received data here

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

}

Answer №2

The server ultimately determines the limitations of the response, making it impossible to restrict server responses using JavaScript alone. Take a look at mrblewog's suggestion and utilize the

jsonplaceholder.typicode.com/photos?_start=0&_limit=5
query parameter for limiting results from jsonplaceholder.

Answer №3

Restricting the API response to only display 6 posts https://exampleapi.com/posts?_limit=6"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing variable values in Google Charts with AngularJS

Hello everyone, I am attempting to display a chart using data obtained from an API. The output of the API is in the form of List<String> and not in JSON format. Here is the snippet of my JS file: google.load('visualization', '1', ...

What causes React JS to continuously render in an infinite loop when using hooks and useState

I am struggling with updating the current state of my component based on a result using a custom hook in React. Whenever I try to update it, I end up in an infinite loop rendering due to my usage of the useState() hook. I am still new to working with Rea ...

Saving the created PDF documents on the server

Utilizing the jsPDF plugin, I am currently generating a .pdf file upon clicking a button to initiate a download. Rather than downloading the file, I would like it to be saved onto my server when the button is clicked. Specifically, I want the file to be sa ...

I am encountering an issue with a JS addition operator while working with node.js and fs library

I'm trying to modify my code so that when it adds 1 to certain numbers, the result is always double the original number. For example, adding 1 to 1 should give me 11, not 2. fs.readFile(`${dir}/warns/${mentioned.id}.txt`, 'utf8', ...

Can we move the "user" object to the forefront and retrieve it from a location other than the "on.AuthSateChanged(user => .... }" function?

Is there a way to define a ref in vuefire to firebase path that relies on the current User object? Can I bring the "user" object to the top level so it can be accessed outside the "on.AuthSateChanged(user => .... }" block? firebase-config.js import * as ...

Troubleshoot: Laravel controller not receiving inputs

I'm currently facing an issue with passing a creation form to a controller. I have set up the route and the ajax call, which is communicating with the route successfully. However, I am encountering a problem where the form values are not being display ...

Changing focus to 'DIV' element without JQuery using Javascript and Angular's ng-click event

Instructions for using an Angular directive to set focus on a "DIV" element when clicked <a href="#" class="skipToContent" ng-click="showContent()" title="skip-to-main-content">Skip To Main Content</a> <div class="getFocus" role="button" ...

Leveraging Async/Await to track error counts across three distinct loops, each invoking an asynchronous function in every iteration

While I have experience with Callbacks, Async/Await and Promises are new concepts to me. In my node.JS server project, I am faced with the challenge of counting errors generated by thousands of asynchronous calls from three different async functions. My g ...

Manipulate audio files by utilizing the web audio API and wavesurfer.js to cut and paste audio

I am currently working on developing a web-based editor that allows users to customize basic settings for their audio files. To achieve this, I have integrated wavesurfer.js as a plugin due to its efficient and cross-browser waveform solution. After prior ...

Retrieving information from an object using a randomly generated identifier

Imagine having an object structured like this. var foo = { "dfsghasdgsad":{ "name":"bob", "age":"27" } }; The variable foo will consistently only have one object, but the key is dynamically created. How can I access the values "bob" and "27" ...

The functionality of an HTML form utilizing JavaScript struggles to function correctly when integrated with PHP

I created a form with JavaScript that allows me to toggle between different fields based on the selection made with radio buttons. <?php require_once 'resources/menus/adminMenu.php'; ?> <div class="col-lg-offset-3 col-lg-6 "> < ...

Implement an AJAX function to prompt a save dialog before initiating the download process

I'm currently programming an embedded device in C with a web server. One of the tasks I am working on is downloading files from this device. I need to download several files at once, so I've set up an AJAX request that uses a POST method and send ...

Guide on implementing the 'cut' feature using electron-localshortcut

Looking for a way to use keyboard shortcuts on Mac without relying on the menu? I recently came across this helpful post: Is it possible to create non-global accelerators without adding them to a menu? Thanks to this informative article, I learned about ...

After props have been passed, the ReactJS ComponentWillMount() function is triggered

Can anyone explain why the child component is only rendered once, even though I pass props to it every time I click a button? Whenever I click a button that passes props to the child, the ComponentWillMount() method of the child component doesn't tri ...

Day Change Triggers React [Native] View Update

I've been working on a React Native component that needs to update itself when the day changes, regardless of user interaction. Is there another method besides using setInterval for this task? If I use setTimeout in my viewDidLoad function with the n ...

Having trouble connecting the controller variable in AngularJS to the HTML page

I'm struggling with a simple query that doesn't seem to be working for me. When making an Ajax call and retrieving data from the backend, everything seems to be in order. Here's the code snippet: $.ajax({ type: "GET", url: service ...

What is the best way to break down this function from props in React?

Forgive me if this question sounds naive, but as I delve into the world of React and useState, I am encountering a scenario where I have a signup function coded. Upon sending a username and password through a POST request to an API endpoint, a response mes ...

Tips for avoiding multiple function calls in React JS when a value changes

How can I avoid multiple function calls on user actions in my demo application? I have tabs and an input field, and I want a function to be called when the user changes tabs or types something in the input field. Additionally, I need the input field value ...

Is there a way to convert an array into a single comma-separated value using parameters?

Is there a way to parameterize an array as a single name-value pair that is comma separated? I have tried using jQuery $.param, but it creates a parameter for each value in the array instead of just one. Unfortunately, it seems that there is no option or s ...

Validation of forms using asynchronous requests in Magento

I've created a form in Magento using code, and it operates with ajax. Now I need to ensure that this form is validated properly. While I'd prefer to tap into Magento's validation features, I'm not sure how to trigger them without submi ...