The latter section of my javascript code fails to run after processing a JSON file

Hi there! I need some assistance understanding why my latest script in this particular file isn't functioning properly. The main goal is for it to extract a value from JSON and compare it with a predefined value. Thank you all so much for your support!

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {

var url = "https://graph.facebook.com/tenniswarehouse?callback=?";


$.getJSON(url,function(json){
    var html = "<div id=\"tester\">" + json.likes + "</div>";
    //A little animation once fetched
     $('.facebookfeed').html(html);

 });
 });
 </script>
 </head>
  <body onload="timeMsg()">
   <div class="facebookfeed">
    <h2></h2>
  </div>
  <script type="text/javascript">
  var x =document.getElementById("tester").innerHTML;
  if (x < 56700) {
  document.write("it's working")
  }
 else {
 document.write("it's not working")
 }
 </script>
 </body>
 </html>

Answer №1

It is essential to encapsulate this code within a function for proper execution:

function myFunc() {
  var x = document.getElementById("tester").innerHTML;
  if (x < 56700) {
     document.write("worked");
  }
  else {
     document.write("didn't work");
  }
}

To ensure correct functionality, call the function as shown below:

$.getJSON(url,function(json){
    var html = "<div id=\"tester\">" + json.likes + "</div>";
    //Add a slight animation after fetching
     $('.facebookfeed').html(html);

     myFunc();
   });

This arrangement is crucial because executing the code before adding "tester" to the DOM can cause issues.

Answer №2

Upon loading the page, your function in the head section is executed. However, any javascript code within the body section is executed as the page is being rendered, which means it runs prior to making an AJAX request.

To resolve this issue, you should transfer the script from the body to the json handler. Here's how you can do that:

$(function() {

    var url = "https://graph.facebook.com/tenniswarehouse?callback=?";

    $.getJSON(url,function(json){
        var html = "<div id=\"tester\">" + json.likes + "</div>";
        //Add a small animation after fetching data
        $('.facebookfeed').html(html);
        var x = document.getElementById("tester").innerHTML;
        if (x < 56700) {
            document.write("worked")
        } else {
            document.write("didn't work")
        }    
    });
});

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

What is preventing the native JSON viewer in Firefox from working with my request?

When I try to view the response to my URL in Firefox JSON viewer, it always displays as plain text. Even though I have set the option devtools.jsonview.enabled to true. I am sending a request with a header Accept: application/json and receiving a response ...

What is the best way to display data received from an AJAX request in a hidden div container?

I recently came across a module while working on a project. Page 1 Users need to use the search bar to navigate to Page 2. Page 2 On Page 2, all fetched results are displayed in divs with checkboxes associated with each result. https://i.sstatic.ne ...

Tips for utilizing your pointer as a writing tool on paper

Looking for a solution to enable drawing on either the entire browser page or a specific portion of it using the mouse pointer. The drawing will consist of a simple blue line that appears upon clicking a button. Are there any alternatives to Flash for thi ...

What is the reason behind the blocking of Ajax GET requests without CORS, while JSONP requests are permitted?

Accessing any page on the web through a GET request using HTML tags from a different origin is possible: <script src="http://example.com/user/post?txt=sample"></script> XHR requests to other origins are blocked for security reasons. For examp ...

Increasing the ID values of items within a nested repeater using AngularJS

In my code, I have a list of questions with corresponding choices. The challenge I am facing is that I need the id values of the choices to increment properly. Specifically, I want the id values to restart counting whenever there is a new question. Most o ...

Angular elements that function as self-validating form controls

I'm wondering if there's a more efficient approach to achieve this, as I believe there should be. Essentially, I have a component that I want to function as an independent form control. This control will always come with specific validation requi ...

Utilizing Node.js and Express to dynamically load context configuration from a database

I have a unique scenario involving a Node.js + Express application connected to a MySQL database. There are specific context configurations that apply to the entire website and all users, which I need to retrieve from the database on each page request (ra ...

When res.write is called before res.send, an error occurs

I'm struggling to figure out why I am getting an error with the following code. app.get("/", (req, res) => { res.write("Hello"); res.send(" World!"); }) // Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers afte ...

What is the best way to utilize Python in order to transform a large amount of unicode into characters to create a string-like appearance?

In JavaScript, I've managed to do this: eval(String.fromCharCode(102,117,110,99,116,105,111,110,32,99,104,101,99,107,40,41,123,13,10,09,118,97,114,32,97,32,61,32,39,100,52,103,39,59,13,10,09,105,102,40,100,111,99,117,109,101,110,116,46,103,101,116,69 ...

What is the best way to incorporate external scripts into a Node.js project?

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.5/socket.io.js"></script> What is the process for adding an external library to a node.js application? I am seeking assistance on how to integrate the following library into my ...

"Concealed beneath the text is the link to return to the

I have implemented a back to top link in my MVC project. Layout: <a id="back-to-top" href="#" class="btn btn-primary btn-lg back-to-top" role="button" title="Click to return to the top of the page" data-toggle="tooltip" data-placement="left"><spa ...

Issue with Angular JS failing to populate HTML content following an HTTP request

Today was my first day diving into AngularJS, following some tutorials on CodeSchool. I checked out this tutorial and this example to get started. The issue I'm facing is that although I successfully retrieved JSON data from the PHP server side (for ...

Where should the webapp files for a Node.js application be located within the server directory?

Can someone help clarify a question I have been struggling with? I have created a nodejs webapp with a specific directory structure, as shown in the screenshot. This app will eventually incorporate MongoDB and store a large number of audio files. I am usi ...

Changing the text color in a React Native TouchableHighlight component

How does TouchableHighlight change the text color when tapped? I have already configured the backgroundColor using underLayColor. Here is my updated code snippet: <TouchableHighlight style={{ borderRadius: 5}} ...

Kendo UI struggling to load nested JSON data

As a beginner in Kendo UI development, I am looking to display this response in a Kendo UI grid. After researching the Kendo API documentation, I noticed the schema mentioned. I was able to load the values successfully, but encountered a problem with my ...

A guide on sending an array to an Express API

I have been working on creating APIs using Express.js and SQL Server. Posting an object was easy and simple, but now I have a new challenge: how do I post an array? Imagine I have a table that only stores two parameters: Table_A Id | CouponId In this ta ...

Implementing custom deserialization for C# DataContracts

Seeking assistance with a DataContract issue. I am working on a web service that generates JSON output which needs to be mapped to a C# object. The crucial data retrieved from the API is nested under a "data" key in the JSON object, but this part is irrel ...

What is the scope parameter for the facebook-node-sdk in node.js?

https://github.com/amachang/facebook-node-sdk I decided to utilize this module in order to create a Facebook-integrated login for my node.js project, following the example provided with express: var express = require('express'); var Facebook = ...

Challenges with converting JSON into PHP code

I am attempting to output the JSON response below to HTML using PHP. Here is the JSON response : { "data": { "onward": [ { "origin": "LHR", "id": "SB15", "rating": 0, "destination": "FKK", "PricingSolut ...

What is the correct syntax for declaring a variable within a switch statement in TypeScript?

How can I properly use a switch statement in TypeScript to assign a new variable a value? For example: let name: string switch(index) { case 0: name = "cat" case 1: name = "dog" .... } I keep getting the err ...