Decoding JSON on 9gag

I am trying to select a random image from the following URL:

In order to display it correctly, I need to determine the size of the image.

I am utilizing YQL to store the JSON result in a variable (referred to as source).

After replacing 'https' with 'http' and removing all backslashes, this is how I proceed:

var it = $.parseJSON(source);
var total = it.count-1;
var random = Math.floor((Math.random()*total)+0);     
var gagurl = it.items[random];
var gagurldecode = gagurl.replace('\\','');
gagurldecode = gagurldecode.replace('https','http'); //this is the image's URL 

Unfortunately, I am unable to retrieve the dimensions of this image.

   var img = new Image();
   img.src = gagurldecode;

The line alert(img.height); does not return anything.

If I change

img.src = gagurldecode;

to

img.src = 'http://d24w6bsrhbeh9d.cloudfront.net/photo/1777377_460s.jpg';

it works fine.

What am I doing incorrectly? PS: Apologies for any mistakes in my English!

Answer №1

This paragraph explains how the JSON data is interpreted and why certain lines of code may be unnecessary due to escaping slashes:

var gagurldecode = gagurl.replace('\\','');

The issue addressed here is that the height and width properties of an image are not immediately available until the image has been fully downloaded and examined. This process can occur asynchronously or synchronously depending on the browser's caching mechanism, as demonstrated in the following example:

img.onload = function() {
    alert(img.height);
}

The conclusion states that this approach will reliably yield the desired results.

Answer №2

What is the purpose of using replace calls in this scenario? It appears unnecessary since the slashes will automatically be unescaped when the string is parsed into JSON. Additionally, your replace calls are not utilizing replaceAll.

You may want to consider trying the following approach:

// Assume str contains the JSON received from the URL
var str = '{"items":["http:\/\/d24w6bsrhbeh9d.cloudfront.net\/photo\/5373376_460s.jpg","http:\/\/d24w6bsrhbeh9d.cloudfront.net\/photo\/2899638_460s_v1.jpg","http:\/\/d24w6bsrhbeh9d.cloudfront.net\/photo\/3196367_460s.jpg","http:\/\/d24w6bsrhbeh9d.cloudfront.net\/photo\/1777377_460s.jpg","http:\/\/d24w6bsrhbeh9d.cloudfront.net\/photo\/3233576_460s.jpg","http:\/\/d24w6bsrhbeh9d.cloudfront.net\/photo\/3101249_460s.jpg","http:\/\/d24w6bsrhbeh9d.cloudfront.net\/photo\/3279498_460s.jpg","http:\/\/d24w6bsrhbeh9d.cloudfront.net\/photo\/2487961_460s.jpg","http:\/\/d24w6bsrhbeh9d.cloudfront.net\/photo\/2693569_460s.jpg"],"layout":"list","count":9}'
var obj = JSON.parse(str);
var src = obj.items[~~(Math.random() * (obj.items.length - 1))];
img.src = src;

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

Show your JSON server data in a Bootstrap datatable within a popup modal

I have a database table and I am looking to showcase the table values in a Bootstrap data table within a modal popup. Main.html <a href="#myModal" id="custId" data-toggle="modal" data-id="special-fy" class="btn btn-primary">Click Here</a> &l ...

Diverse Range of Exports Available in React Component Library

I have been working on developing a component library consisting of multiple independent components. My objective is to enable users to easily import and use these components in their projects, similar to the following: import One from 'component-lib ...

Why does Visual Studio Code auto-complete "ImagePropTypes" when typing a dot after "props"?

Currently following a React Native tutorial with Visual Studio Code. Using Babel Javascript as my selected language mode. Encountering an issue when typing Line 7: https://i.stack.imgur.com/WcV7B.png After adding a period (.) to props, it changes to Ima ...

Using jQuery to send information to PHP via an AJAX request

When attempting to use jQuery to send form data to a PHP file, nothing happens when the button is pressed. The jQuery code snippet: $(document).ready(function(){ $("#daily_user_but").click(function(){ $('#result').html('<im ...

The smooth scroll feature is not functioning properly on the animated mouse-scroll down button

I've recently added an Animated Mouse Scroll Down button on my website. However, when I click the button, the smooth scroll feature is not working as expected. Important Note: I already have a separate button for navigating to the next section where ...

Retrieve the chosen item from the autocomplete feature

Unfortunately, I have encountered an issue with this solution as I was unable to get it to work correctly in my code. The objective is to retrieve the selected item and then call another function to utilize it. The script is as follows: <script type=" ...

In a React application, the input field unexpectedly loses focus after typing just one character

Has anyone encountered an issue with a dropdown menu causing input field focus to be lost after typing one character? I've attempted setting unique keys for each field, but it hasn't resolved the problem. For reference, here is the link to the p ...

Ensuring the dropdown menu's functionality in AngularJS

I'm currently working on a code snippet that validates when the user moves away from a specific select element. The goal is to change the border color of the select element to either red or green only when the user tabs away from it or moves the mouse ...

Display routes in React using the react-router package

Can I use a console command at runtime to display all routes in my application? Despite utilizing react-router, not all routes seem to be functioning properly. In Rails, you can retrieve a list of routes during runtime. ...

Is it possible to deactivate dynamic binding in Vue.js?

I'm curious if there's a way to disable dynamic binding for a specific instance of an attribute that I'm displaying. Imagine I have the following code, utilizing two-way binding: this.$children[0].$data.hits In this scenario, I have a vac ...

Encountering a rollbackFailedOptional error during the NPM Install process

When attempting to use various command prompts like Windows Powershell, command prompt as an admin, and bash CMD, I encountered the same error message after trying to run npm install: npm install npm@latest -g The specific error message was: [...] / ro ...

Generating an Xpath for the selected element with the help of Javascript or Jquery - here's how!

On my website, I have implemented a click event on an element. When a user clicks on this element, I want to generate the XPath of that particular element starting from either the html or body tag, also known as the Absolute Xpath. For example, if I click ...

Optimize your mobile experience by creating a notification menu that is scrollable and fixed in position

Recently, I purchased Moltran, but encountered a major issue: The notification menu disappears on mobile devices, which is not ideal for me. After some research, I discovered that removing the hidden-xs class from the li notification element can solve this ...

What is the best way to replicate the Ctrl+A action on an element using jQuery or JavaScript?

Is there a way to trigger the Ctrl+A key combination in a textarea element when a specific event occurs, without resorting to caret positioning or selecting all text separately? I'm looking for a method that simulates hitting Ctrl+A using a cross-brow ...

Is there a way to refresh the animation on dougtesting.net?

I'm working with the dougtesting.net library to create a spinning wheel. I've been trying to figure out how to reset the animation once it finishes, but I can't seem to find any information on it. My goal is to completely clear all states so ...

Utilizing UI-GRID to showcase JSON information

I am currently in the process of fetching data from the server. [ { id:1, name:demo, request: { id: 1, localCompany: { id: 1 } } }] [{ }, { }] This is how my JSON object appears to be structured. After calling ...

Concealed Input Enhancements for AutoComplete

Hey there! I'm new to AJAX and could really use some help with my autocomplete function. I'm trying to store the ID of the user's selection in a hidden input field, but I've hit a roadblock. So far, my function isn't working as exp ...

Switch off any other currently open divs

I'm currently exploring a way to automatically close other div's when I expand one. Check out my code snippet below: $( document ).ready(function() { $( ".faq-question" ).click(function() { $(this).toggleClass('open'); $(this ...

Enhancing collection json by utilizing withCount

I have a scenario where I have two models, Client and Project. The Client model has a hasMany relationship with projects. I am trying to include the project count for each client in the JSON response but I am encountering some difficulties. In my controll ...

Creating a dynamic dropdown menu using JQuery that does not automatically submit the form when a value is

Upon selecting a background color from the dropdown menu, I am generating a dynamic dropdown for text colors. The Text Color dropdown is populated correctly based on the selection of Background Color. Although the functionality works as intended, I encoun ...