Is there a way to limit the number of items displayed in the feed to just 10 using the Flickr API?

I am currently utilizing the Flickr API to showcase some images, however I only want to display 10 or fewer items in the feed results. How can I limit the number of items displayed to less than 10 without seeing a limit parameter?

https://api.flickr.com/services/feeds/photos_public.gne?tags=rat&format=json&callback=?

The API currently returns 20 items, but I require only 10 or less.

Below is a snippet of the code being used:

$.getJSON("https://api.flickr.com/services/feeds/photos_public.gne?tags=rat&format=json&callback=?",function(json){
  console.log("done");
});

function jsonFlickrFeed(data) {
  

  console.log(data.items.length);
  for(var i=0;i<data.items.length; i++){
      console.log(data.items[i]['media']['m']);
  }
}

I also aim to achieve this using a native JS ajax call without jQuery, but encountering errors during execution.

var url = "https://api.flickr.com/services/feeds/photos_public.gne?tags=rat&format=json&callback=?";

xhr = new XMLHttpRequest;
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        var data = JSON.parse(xhr.responseText);
        console.log(data);  
    }else {
       console.log("error"); 
    }
}
xhr.open("GET", url)
xhr.send();

Answer №1

Upon reviewing the Flickr API Service page for the method

https://api.flickr.com/services/feeds/photos_public.gne
, I couldn't find a limit parameter specified.

https://i.sstatic.net/JU4p7.png

Nevertheless, you can actually limit the number of results displayed within a loop. Despite this limitation, all results from the

https://api.flickr.com/services/feeds/photos_public.gne
method will still be fetched in the background.

Here is an example:

(function() {
  var form = document.getElementById("form");
  form.onsubmit = function(e) {
    $.getJSON("https://api.flickr.com/services/feeds/photos_public.gne?tags=rat&format=json&callback=?", window.jsonFlickrFeed);
    e.preventDefault();
  };
})();

window.jsonFlickrFeed = function(data) {
  var i, len = data.items.length, html = "", limit = document.getElementById("txtLimit").value * 1;
  for (i = 0; i < limit; i++) {
    html += "<img src=\"";
    html += data.items[i].media.m;
    html += "\" />";
  }
  document.getElementById("list").innerHTML = html;
};
#list {
  border: solid 1px #ccc;
}

#results img {
  padding: 5px;
  width: 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="form">
  <label for="txtLimit">Limit:</label>
  <input id="txtLimit" min="0" type="number" value="0" />
  <button type="submit">Send</button>
  <hr />
  <div id="list"></div>
</form>

Update:

jQuery works with JSONP while pure JavaScript XMLHttpRequest does not due to how jQuery.getJSON() handles the resource as if it were a script. https://i.sstatic.net/2z4wv.png

Despite the absence of Access-Control-Allow-Origin: * in the response headers, it doesn't pose any issue in this context. The script can still be requested using:

<script src="https://api.flickr.com/services/feeds/photos_public.gne?tags=rat&format=json&callback=?" type="text/javascript"></script>

Make sure to check the

content-type: application/javascript;
.

https://i.sstatic.net/G1aYQ.png

The response from the URL is a function named jsonFlickrFeed(Object parameter) where the parameter is in JSON format.

{
  "title": "Recent Uploads tagged rat",
  "link": "https:\/\/www.flickr.com\/photos\/tags\/rat\/",
  ...
}

https://i.sstatic.net/Ngpyn.png

To achieve this functionality using Native JavaScript and JSONP, you need to create a function that calls the URL through a script tag to run the jsonFlickrFeed({}) function.

Demo: Native JavaScript + JSONP:

(function() {
  function request(url, callback) {
    var head = document.head, script = document.createElement("script");
    script.src = url;
    script.type = "text/javascript";
    head.appendChild(script);

    // Remove the script tag after it's loaded once.
    script.onload = function() {
      this.remove();
    };
    window[callback] = function(data) {
      var i, len = data.items.length,
        html = "",
        limit = document.getElementById("txtLimit").value * 1;
      for (i = 0; i < limit; i++) {
        html += "<img src=\"";
        html += data.items[i].media.m;
        html += "\" />";
      }
      document.getElementById("list").innerHTML = html;
    };
  }

  var form = document.getElementById("form");
  form.onsubmit = function(e) {
    e.preventDefault();
    var url = "https://api.flickr.com/services/feeds/photos_public.gne?tags=rat&format=json&callback=?";

    request(url, "jsonFlickrFeed"); 
  };

})();
#list {
  border: solid 1px #ccc;
}

#results img {
  padding: 5px;
  width: 50%;
}
<form id="form">
  <label for="txtLimit">Limit:</label>
  <input id="txtLimit" min="0" type="number" value="0" />
  <button type="submit">Send</button>
  <hr />
  <div id="list"></div>
</form>

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

Can external URLs be utilized in Firebase hosting for AJAX or HTTP requests?

I am curious to know if Firebase has the ability to use external URLs: defaultUrl: externalExampleUrl: $.ajax({ url: 'https://us-central1-ecc-local.cloudfunctions.net/getAjax', dataType: "json", type: 'POST', data: { ...

Exploring Next.js: Leveraging fetch to retrieve data in getServerSideProps and passing it to the client via query parameters

I'm utilizing a getServerSideProps function on the directory page. pages/catalog/index.js export async function getServerSideProps(ctx) { const response = await fetch( `http://someDomen.com/api/ipro/catalog?${ctx?.query?.page ? `page=${ctx.quer ...

Is there a way to set up a local npm module directory without using symlinks

Here is a breakdown of the file structure in a simple way. /my-module ..package.json /my-app ..package.json I am trying to have my-app install my-module locally. This is what I have attempted: "dependencies": { "myModule": "../my-module" } The opti ...

Jest fails to pass when encountering the double colon

Having issues testing a React app using Jest. I encounter errors when running my code: FAIL src\App.test.js ● Test suite failed to run C:/Users/user1/Projects/map-editor/src/App.js: Unexpected token (40:33) 38 | <div cla ...

Issues with Three.js raycaster intersectObjects

I am currently working on a 3D scatter plot where spheres are used to represent the points, and I am attempting to show information from the points when they are clicked. After researching various answers on this platform, I believe I am moving in the righ ...

Receive immediate updates of the text input in real-time using the onkeydown event handler in Javascript

I attempted to display the content of the input box in a message div simultaneously, however, the output always seems to be one step behind. function showWhatsWritten(){ var tempText; tempText = document.getElementById("text").value; document.getEle ...

Is there an issue with the JavaScript functionality of the max/min button?

Help needed with maximize/minimize button functionality as my JavaScript code is not working. Any suggestions for a solution would be greatly appreciated. Thank you in advance. Below is the code snippet: <html> <head> <script> $(functio ...

Unable to close window with window.close() method after initially opening it with JS or JQuery

I am currently using an Instagram API that requires users to log out through the link . This link redirects users to the Instagram page, but I want them to be redirected to my own page instead. Although I tried different methods from a previous post on thi ...

Unable to display numerous bars on the x-axis in vue-chartjs

Having trouble displaying a stacked bar chart with two bars sharing a label on the x-axis. The issue is that the 2nd bar sits below the first one (if you hide the 2021 value, the 2022 bar will appear): var barChartData = { labels: ["January", "Febru ...

Exploring the concept of Promises through the lens of recursion

I am dealing with a MongoDB collection that looks like this [ { "classId": "1", "name": "Input", "definition": [ { "property": [ { "classId": "12", "name": "One" }, { ...

Determine in React whether a JSX Element is a descendant of a specific class

I am currently working with TypeScript and need to determine if a JSX.Element instance is a subclass of another React component. For instance, if I have a Vehicle component and a Car component that extends it, then when given a JSX.Element generated from ...

Reactjs Router.push function does not behave as intended

I'm currently working with Reactjs and Next.js. I am experiencing an issue where the correct data is only displayed after refreshing the page instead of upon clicking, as intended. To solve this problem, I have attempted to use "router.push", but unfo ...

Unexpected behavior observed with LitHTML when binding value to input type range

Currently, I am working on an implementation that involves using range inputs. Specifically, I have two range inputs and I am trying to create a 'double range' functionality with them. The challenge I am facing is related to preventing one slider ...

Oops, looks like the server is experiencing some technical difficulties. The request is taking too long to process and has timed out

I find myself in a predicament with my shared hosting. Despite modifying my ajax requests to be smaller and adding timeouts after each request, the issue persists. How can I resolve this problem while using shared hosting? Note: set_time_limit(0); is not p ...

retrieving JSON data within the controller

When I use the command console.log($scope.data), I am able to view my JSON file. Additionally, by using <div ng-repeat="item in data">, I can see all the items in the view. However, when I try console.log($scope.data[0]) or console.log($scope.data[0] ...

Creating a fetcher that seamlessly functions on both the server and client within Nextjs 13 - the ultimate guide!

My Nextjs 13 frontend (app router) interacts with a Laravel-powered backend through an api. To handle authentication in the api, I am utilizing Laravel Sanctum as suggested by Laravel for SPAs. This involves setting two cookies (a session and a CSRF token) ...

Emberjs: Developing a self-focusing button with Views/Handlebar Helpers

Currently, I am using a Handlebars helper view that utilizes Em.Button (although it's deprecated) to create a Deactivate Button. This button is designed to focus on itself when it appears and clicking it triggers the 'delete' action. Additio ...

How to Stop the Window from Closing with jQuery

Is there a way to prompt the user for confirmation before they leave the page if they click the close button, similar to how it's done in Google Docs? How can this be achieved using jQuery? ...

Error 400 encountered in Spring MVC with Ajax

I am working on a Java application using Spring MVC and encountering some issues with sending AJAX requests to a Spring controller. I have noticed that when I include the headers "Accept", "application/json" and "Content-Type", "application/json;charset=ut ...

problems encountered while trying to increment ng-click function in Angular JS and Ionic

I'm currently working on developing a quiz using Angular JS and Ionic Framework. However, I've encountered an issue: The "Continue" button is not functioning as expected when clicked (using ng-click) to move to the next question. &l ...