Struggling to retrieve JSON response through Javascript

It seems there may be an issue with the API URL or headers in the code provided below. The isError function is always triggered, indicating a lack of response. However, testing the same API URL in Postman returns a successful response.

Code:

//loading Flickr Photos through their API
$(document).ready(function() {
    getFlickrJSON();
});

function getFlickrJSON () {
    $.ajax({
        method: 'GET',
        url: 'https://api.flickr.com/services/feeds/photos_public.gne',
        data: {
            format: "json"
        },
        dataType: 'json',
        success: onSuccess,
        error: onError
    })
}

function onSuccess(jsonReturn) {
    var fadeInT = 1000;

    for(var i = 0; i<jsonReturn.data.children.length; i++) {

        var items = jsonReturn.data.items[i].data;
        var photo = [];
        var photoTitle = items.title;
        var author = [];
        var description = [];
        var tags = [];

        var loadthis = 
            "<p class='photoTitle'>" + photoTitle + "</p>";
        $(loadthis).hide().appendTo($('.photo_tile')).fadeIn(fadeInT);
    }
    console.log('success');
}

//handling JSON failure
function onError(){
    $('.photo_tile').html('No data found');
    console.log('error');
}

//Response

jsonFlickrFeed({
    "title": "Uploads from everyone",
    "link": "https:\/\/www.flickr.com\/photos\/",
    "description": "",
    "modified": "2018-11-15T09:38:29Z",
    "generator": "https:\/\/www.flickr.com",
    "items": [{
        "title": "Port sainte-rose , \u00eele de la R\u00e9union",
        "link": "https:\/\/www.flickr.com\/photos\/156645216@N05\/30950648007\/",
        "media": {"m":"https:\/\/farm5.staticflickr.com\/4857\/30950648007_eec58dca53_m.jpg"},
        "date_taken": "2018-10-25T14:54:36-08:00",
        "description": " <p><a href=\"https:\/\/www.flickr.com\/people\/156645216@N05\/\">Nellouille974<\/a> posted a photo:<\/p> <p><a href=\"https:\/\/www.flickr.com\/photos\/156645216@N05\/30950648007\/\" title=\"Port sainte-rose , \u00eele de la R\u00e9union\"><img src=\"https:\/\/farm5.staticflickr.com\/4857\/30950648007_eec58dca53_m.jpg\" width=\"240\" height=\"240\" alt=\"Port sainte-rose , \u00eele de la R\u00e9union\" \/><\/a><\/p> ",
        "published": "2018-11-15T09:38:29Z",
        "author": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="432d2c212c273a03252f2a2028316d202c2e">[email protected]</a> (\"Nellouille974\")",
        "author_id": "156645216@N05",
        "tags": ""
   },
   {
        "title": "[New post] Design Baju Korporat Vector",
        "link": "https:\/\/www.flickr.com\/photos\/48423781@N04\/30950648667\/",
        "media": {"m":"https:\/\/farm5.staticflickr.com\/4871\/30950648667_5f5837059f_m.jpg"},
        "date_taken": "2018-11-15T01:38:32-08:00",
        "description": " <p><a href=\"https:\/\/www.flickr.com\/people\/48423781@N04\/\">Fadzil Aripin<\/a> posted a photo:<\/p> <p><a href=\"https:\/\/www.flickr.com\/photos\/48423781@N04\/30950648667\/\" title=\"[New post] Design Baju Korporat Vector\"><img src=\"https:\/\/farm5.staticflickr.com\/4871\/30950648667_5f5837059f_m.jpg\" width=\"32\" height=\"32\" alt=\"[New post] Design Baju Korporat Vector\" \/><\/a><\/p> <p>via Creeper Design 03 6143 5225 <a href=\"https:\/\/ift.tt\/2Puetac\" rel=\"nofollow\">ift.tt\/2Puetac<\/a><\/p>",
        "published": "2018-11-15T09:38:32Z",
        "author": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="95fbfaf7faf1ecd5f3f9fcf6fee7bbf6faf8">[email protected]</a> (\"Fadzil Aripin\")",
        "author_id": "48423781@N04",
        "tags": "new post design baju korporat vector"
   }]
})

Answer №1

If you're encountering a CORS issue, one solution is to either use a Chrome extension or spoof it in an AJAX request.

$.ajax({
     method: 'GET',
     url: 'https://cors-anywhere.herokuapp.com/https://api.flickr.com/services/feeds/photos_public.gne?format=json',
     "headers": {
        "origin": "https://flickr.com",
     },
     success : function(res){
        console.log(res)
     }
})

Keep in mind that while this will spoof the request for you, setting the header "origin" can be unsafe.

I hope this information proves useful to you.

Answer №2

You have overlooked a crucial parameter in your query.

'https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?',

For more information, refer to this fiddle https://jsfiddle.net/2gz8uqws/

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 you explain the syntax for the Javascript tag?

While browsing through some code, I stumbled upon this snippet and found myself puzzled by the not:. Is it a tag of some sort? And if so, are there alternative applications for it? var foo = { not: function(bool) { return !bool; } } I'm curious t ...

When attempting to print a Rectangle on my webpage using JavaScript and taking user input, I encountered an error stating that 'str' is not defined

I'm trying to implement a feature where clicking on the "try it" button will prompt the user for the number of lines and then print that many lines in the form of a rectangle. However, when I run my code, nothing appears on the DOM and there is an err ...

Error: React/Express - The renderToString() function encountered an unexpected token '<'

As I work on implementing server-side rendering for my React/Express application, I have hit a snag due to a syntax error related to the use of the react-dom/server renderToString() method. In my approach, I am following a tutorial mentioned here - The sn ...

What is the best way to calculate the number of squares required to completely fill a browser window in real-time?

I am creating a unique design with colorful squares to cover the entire browser window (for example, 20px by 20px repeated both horizontally and vertically). Each square corresponds to one of 100 different colors, which links to a relevant blog post about ...

Unable to access property 'name' of null object

I'm currently learning how to build a local library app using Express with The Odin Project's tutorial. Below are the relevant parts of my code: In routes/catalog.js, I have this: router.get("/books", book_controller.book_list); In models/book. ...

Preserve the chosen option in a dropdown menu even after a postback using JavaScript

Seeking Help in Retaining Dropdownlist Selected Value After Postback In my efforts to retain a dropdownlist selected value after postback, I have been exploring various methods. I extract the selected values from the dropdownlist and store them in local ...

A vibrant loading animation within a pop-up window

I have implemented an ajax spinner on my page using the following code: $(document) .ajaxStart(function () { $loading.show(); }) .ajaxStop(function () { $loading.hide(); }); Now, I want to display the spinner ...

Problem with sending JSON-encoded arrays to an API

After successfully connecting to an API via Postman, I encountered an issue with my AJAX call. The error message returned is: Object {status: false, message: "Add amenities in JSON string"} The problem seems to be related to the amenities parameter, as ...

How to resolve the error of "Cannot GET /api/courses/1"

const express = require('express'); const app = express(); app.get('/',(req,res) =>{ // viewable at localhost:3000 res.send('hello world'); }); app.get('/api/courses',(req,res) =>{ // shown on ...

Convert a string to HTML using AngularJs

Snippet: <tr ng-repeat="x in orderCsList"> <td class="ctn"><input type="checkbox" ng-model="x.checked"></td> <td class="ctn">{{ x.wdate }}</td> <td class="text-left">{{ x.wid }}</td> <td class="te ...

Tips for passing a parameter (such as an ID) through a URL using ng-click to display a subdocument belonging to a particular user in

I am looking to retrieve specific user subdocument data on a separate page by passing the id parameter in a URL using ng-click in AngularJS. <tr ng-repeat="register in registerlist | filter:searchText"> <td>{{$index+1}}</td> <td&g ...

What is the proper way to declare a Type for a JSX attribute in Google AMP that utilizes square brackets?

When utilizing AMP's binding feature, you must apply specific attributes that encapsulate an element's property with square brackets and connect it to an expression. An example from AMP is shown below: <p [text]="'Hello ' + foo"> ...

Sending data from frontend to backend in a Node.js Express application

My Node.js Express project in the WebStorm IDE is structured like this: I'm trying to find a way to pass a variable from index.js to app.js so that I can write it to data.json at the end. As a beginner in Node.js, I'm still grappling with the c ...

Utilize JavaScript to extract content from a text file and showcase it in a Bootstrap modal pop-up through knockout binding

I'm currently working on a function that reads data from a .txt file (located in the website's root directory) and then displays it in a modal dialog box. I believe I've made progress as the file is recognized during debugging, but unfortuna ...

Error message: 'firebase/app' does not export 'app' (imported as 'firebase') - Import attempt failed

Encountered a strange issue today. As I tried to import firebase, an error popped up: ./node_modules/firebaseui/dist/esm.js Attempted import error: 'app' is not exported from 'firebase/app' (imported as 'firebase'). The setup ...

Is it not possible to include Infinity as a number in JSON?

Recently, I encountered a frustrating issue that took an incredibly long time to troubleshoot. Through the REPL (NodeJS), I managed to replicate this problem: > o = {}; {} > JSON.stringify(o) '{}' > o.n = 10 10 > JSON.stringify(o) ...

When attempting to change an image using JavaScript, the image fails to load

I am having trouble understanding what is wrong with my code. <html> <body> <script type="text/javascript"> function changeImage() { var image = document.getElementById('myImage'); if (image.src.match("bulbon")) { ...

Mastering the correct way to handle the "window" object within the Node.js testing environment using JSDom

Testing my React app using Tape and JSDom involves importing a specific module at the beginning of each test JS file: import jsdom from 'jsdom' function setupDom() { if (typeof document === 'undefined') { global.document = jsdom ...

Is there a way to automatically advance to the next question in Surveyjs without needing to click the Continue

I'm currently integrating SurveyJs into my web application. The first 3 pages of my survey contain HTML elements that I would like to automatically slide after a few seconds, similar to the functionality on the following sample site using SurveyJS: O ...

A messaging application powered by socket.io and the Express JS framework

I am currently learning Node.js and I am encountering an issue with using socket.id to identify logged in users on the client side using their email id and password. The verification process happens on the server side, and if successful, the user's so ...