Having trouble getting the if statement to run with JavaScript Closures?

Check out this code snippet:

let url = URL;
let imageURL = '';

$.getJSON("https://graph.facebook.com/?id="+encodeURIComponent(url)+"&scrape=true&method=post",
  function (data) {
    let json_data = JSON.stringify(data); 
    json_data = json_data.replace(/\s+/g, ' '); 
    let obj = jQuery.parseJSON(json_data);
    imageURL = obj.image[0].url;
    alert(imageURL+'Facebook');

    if(imageURL == ''){
      $.getJSON("//query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20html%20WHERE%20url=%27"+encodeURIComponent(url)+"%27%20AND%20xpath=%27descendant-or-self::meta%27&format=json&callback=?"
      , function(data) {
          let res = $.grep(data.query.results.meta, function(image, key) {
          return image.hasOwnProperty("property") && image.property === "og:image"
        });
       if (res.length > 0) {
         let imageURL = res[0].content;
         alert(imageURL+'Pinterest');
      });
    }
});

Sometimes the code works fine, but there are certain cases where it fails, such as with URLs from Phandroid like

http://phandroid.com/2015/09/25/galaxy-s7-february/
.

In these cases, the first method fails to get obj.image[0].url; since the JSON object doesn't exist. Since imageURL was initially blank, the if condition should execute but it doesn't. No alerts are triggered in this scenario. How should I proceed?

Answer №1

Why not give this a shot:

const websiteURL = URL;
let imageURL = '';

$.getJSON("https://graph.facebook.com/?id="+encodeURIComponent(websiteURL)+"&scrape=true&method=post",
  function (data) {
    // parse JSON; // <-- please correct this
    imageURL = obj.image[0].url;
    alert('Facebook');

    if(imageURL == ''){
      $.getJSON("//query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20html%20WHERE%20url=%27"+encodeURIComponent(websiteURL)+"%27%20AND%20xpath=%27descendant-or-self::meta%27&format=json&callback=?"
    , function(data) {
        // parse JSON; // <-- please correct this
        imageURL = 'insert image here.'// <-- please correct this
        alert('Yahoo');
      });
    }

  });

Answer №2

It's a mystery how your code managed to work at times, considering that when you initiate a request using $.getJSON, it fetches the data asynchronously while the rest of your code continues to run. A more effective solution would be

var url = URL;
var imageURL = '';

$.getJSON("https://graph.facebook.com?id="+encodeURIComponent(url)+"&scrape=true&method=post",
function (data) {
    parse JSON;
    imageURL = obj.image[0].url;
    alert('Facebook');

    // Perform any necessary validation on the image url here
    if(imageURL == ''){
        $.getJSON("//query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20html%20WHERE%20url=%27"+encodeURIComponent(url)+"%27%20AND%20xpath=%27descendant-or-self::meta%27&format=json&callback=?"
        , function(data) {
        parse JSON;
        imageURL = Set the value here.
        alert('Yahoo');
        });
    } else {
        alert('Invalid image url');
    }
});

This way, the block related to Yahoo will execute only after the Facebook block has finished processing.

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

Creating linear overlays in Tailwind CSS can be achieved by utilizing the `bg-gradient

Is there a way to add a linear background like this using Tailwind CSS without configuring it in tailwind.config.js? The image will be fetched from the backend, so I need the linear effect on the image from bottom to top with a soft background. Here are ...

Using Angular 4 to import an HTML file

I am trying to save test.svg in a component variable 'a' or svgicon.component.html. To achieve this, I have created the svgicon.component.ts file. However, it's not working. What steps should I take next? svgicon.component.ts import ...

Is the mounted hook not being triggered in a Nuxt component when deploying in production (full static mode)?

I have a component that is embedded within a page in my Nuxt project. This particular component contains the following lifecycle hooks: <script> export default { name: 'MyComponent', created() { alert('hello there!') }, ...

Embracing the beauty of incorporating nested quotations

I've been experimenting with jquery's append functions lately. I'm adding a substantial amount of html, specifically a button with an onclick event function. It might sound complicated, but due to some technical restrictions, this is my onl ...

Steps to retrieve a specific key value from each object in an AJAX request

I am looking to extract the "url" key and its value from the provided code and save it in a variable. I have attempted different methods to isolate the url key as seen in my commented-out code. $.ajax({ type: 'GET', url: "url", // data: da ...

Avoid clicking on links while the webpage is still loading

I am facing an issue with my website where I need to intercept link-clicking events using jQuery. Everything works fine, but there is a problem if a user clicks on a link before JavaScript finishes loading, causing it to redirect to another page in error. ...

Is there a way to utilize req.query, req.params, or req.* beyond its original scope without the need to store it in a database?

Looking to streamline my code and apply the DRY pattern, I've been working on creating a helper function for my express http methods. The structure of each method is similar, but the req.params format varies between them. Here's how I attempted t ...

What is the best way to include the title "addmoves" to the server using AngularJS?

https://i.sstatic.net/yR2fk.png Furthermore, I am looking to include a button that allows users to add additional movies. The goal is to input multiple sets of data simultaneously, such as: newMovies = [ { movieName:"", director:"", release ...

Problem encountered while parsing JSON data

As I dive into the world of Python, I've been given a task to create some simple database-related scripts using Python. My current hurdle lies in working with JSON within my SELECT script. The specific data format required is as follows; { "Data ...

The function $scope.removeNinja cannot be found

As a beginner in Angular, I encountered an issue while working on a project that involved creating a Directory of ninjas with various functionalities implemented using Angular. Here is a snippet of my HTML file: <!DOCTYPE html> <html lang="en" n ...

The problem with legends in chart.js not displaying properly

I've been struggling to display the labels "2017" and "2018" as legends on the right side of the chart. I've tried numerous approaches but haven't found a solution yet. The purpose of showing these legends is to easily identify that each co ...

Tips for creating a div that slides from the right side to the left side

I received a code from someone and I need help with making the sliding div slide from right to left. Essentially, I want the div to hide on the right side and slowly move to the left within a width of 300px. Here is the HTML code: <a id="loginPanel"&g ...

``The background color will dynamically change according to the result of a function

My function named shift_color generates different color codes like "#FF5F74", "#5FFF66", and "#5F8AFF". I am looking to use this output to style a navigation menu background. I have tried the following code: .topnav { background-color: <?php echo shi ...

Is there a way to access the origin of an iframe?

I am facing a challenge with an HTML page that includes an iframe. Within the iframe, there are text and buttons that trigger onclick scripts. However, I'm having difficulty retrieving the values of getBoundingClientRect when I specify the ID of the b ...

Resuming AJAX requests after being aborted

Hey everyone, I'm curious to know if it's possible to resume interrupted ajax requests. I have an array of ajax calls stored as defferreds like this: var defferreds = []; defferreds.push( $soap.ajax({ type: "POST", dataType: ...

Confirmation message is displayed upon clicking to delete a row in the editable Gridview, prompting the user to

One issue I am facing is with a Delete button in an editable Gridview on my ASP.NET application. When the delete button is clicked, it triggers a function that displays a confirmation popup asking the user for feedback on whether they want to proceed with ...

Issue with @RequestParam validation in Spring 3.2 causing HTML output instead of expected JSON

Here is a snippet of code from the spring controller used for a REST API: @RequestMapping(value = "/addExpense", method = RequestMethod.POST, produces="application/json") public void createExpense( @RequestParam(value="expenseDate" ,required= ...

Could someone clarify why EventEmitter leads to issues with global variables?

I recently encountered an error that took me some time to troubleshoot. Initially, I decided to create a subclass of EventEmitter In the file Client.js var bindToProcess = function(func) { if (func && process.domain) { return process.domai ...

Avoiding the "urls" format using the onBeforeRequest function

chrome.webRequest.onBeforeRequest.addListener(function(details) { if (localStorage.on == '1') { return {cancel:true}; } }, {urls: ["*://*.domain1.net/*","*://*.domain2.com/*","*://*.domain3.com/*"], types: ["script","xmlhttpreques ...

Is there a way to determine if a container is overflowing at the top?

Currently, I am using Puppeteer to scrape Slack. My goal is to confirm whether I have scrolled to the very top of the channel feed. The issue arises because the channel feed does not actually scroll, making it impossible for me to utilize the method outli ...