Is Meteor rejecting div calls when not inside getJson?

Recently, I had a rather interesting encounter with Meteor.js. Let me walk you through my code snippet:

Template.mytemplate.rendered = function(){

$.getJSON('http://ip-api.com/json/?callback=?', function(lingo){
$('.location').text(" " + lingo.zip + ", " + lingo.city);
});
};

Essentially, I am utilizing an API to fetch JSON data and display it within my $('.location') element. This part of the code functions as expected. However, the following code does not seem to work.

var tree = $('.location').text();
$('.repeat').text(tree);

More specifically, this code fails when placed outside the getJSON function. For instance...

Template.mytemplate.rendered = function(){

$.getJSON('http://ip-api.com/json/?callback=?', function(lingo){
$('.location').text(" " + lingo.zip + ", " + lingo.city);
});


var tree = $('.location').text();
$('.repeat').text(tree);
};

results in an empty div class="repeat". Curiously, if I rearrange the code as follows...

Template.mytemplate.rendered = function(){

$.getJSON('http://ip-api.com/json/?callback=?', function(lingo){
$('.location').text(" " + lingo.zip + ", " + lingo.city);

var tree = $('.location').text();
$('.repeat').text(tree);

});
};

Suddenly, I can access the content within my div class="location" and transfer it to my div class="repeat". The reason behind this peculiar behavior eludes me.

I would prefer not to limit myself to placing my div manipulations strictly within the getJSON function whenever they involve JSON content.

Answer №1

Before initializing the '.location' element, your jQuery code to copy the location into a repeat element will be executed.

// The 'rendered' method is from the old API.
Template.mytemplate.onRendered(function(){

$.getJSON('http://ip-api.com/json/?callback=?', function resultFn(lingo){
  //2. This code will be executed after some time
  $('.location').text(" " + lingo.zip + ", " + lingo.city);
});

  //1. Code below will be executed first
  var tree = $('.location').text();
  $('.repeat').text(tree);
});

Why? The "getJSON" call takes some time to execute as it fetches external data over the network. Therefore, your callback "resultFn" will have a delay in execution, leading to the last two lines being executed first.

Furthermore, using jQuery to insert data into a template isn't considered the proper Meteor way. A better solution might look like this:

<template name="myTemplate">
  <div class="location">
  {{location}}
  </div>

  <div class="repeat">
  {{location}}
  </div>
</template>

And for the logic:

Template.myTemplate.onCreated(function(){
     this.location = new ReactiveVar(); //using the reactive-var package
     var self = this;
     $.getJSON('http://ip-api.com/json/?callback=?', function(lingo) {
        self.location.set(lingo.zip + ", " + lingo.city);
     });
});

Template.myTemplate.helpers({
  location: function(){
    return Template.instance().location.get();
  }
});

Now, your data will render reactively and can be changed at any time by updating the value of the reactive variable.

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

jQuery Ajax comes with a built-in method for validating serialized forms. This method allows

After creating a form and serializing it to send to my MVC Action method, here is how my jQuery Ajax script looks: $('#submit').click(function () { var jsonObj = $('#form').serialize(); alert(jsonObj); $.ajax({ ty ...

ADFS - asynchronous communication requests

Is it possible to send asynchronous requests in ADFS adapter? Currently, when I fill out data on an HTML page and press send, the response does not come immediately and the page is blocked for a while. Is there a way to prevent this delay? I have considere ...

The Jquery UI dialog refuses to close when the Inner Application is closed

I'm facing an issue with a jQuery dialog box. I have set up a division under the dialog, and within that division, I've loaded an Iframe that contains a URL. The problem arises when I click the close button on the URL window - the dialog box re ...

Error: The variable "require" cannot be located

I'm having trouble loading the node_modules onto one of my webpages. Despite having npm and node.js installed, I keep getting a ReferenceError when trying to use the require() function to initialize Firebase on my website. ReferenceError: Can' ...

Another option in place of MicrosoftAjax using JQuery

Currently, I am utilizing <script src="../../Scripts/MicrosoftAjax.js"></script> <script src="../../Scripts/MicrosoftMvcAjax.js"></script> <script src="../../Scripts/jquery-1.8.3.js"></script> However, the MicrosoftAja ...

Searching with Elastic for shared keywords across various classifications

Using Elastic Search to retrieve tag counts for a group of questions. Here is an overview of the mapping: schoolId schoolname question1 tags(array) tagId , tagStr tagid , tagStr tagid , tagS ...

What is the reason for the blank first page when printing with vue-html2pdf, a tool that utilizes html2pdf.js internally?

Hey there, I'm currently experiencing issues with printing using a Vue component named vue-html2pdf. Here are the problems I'm facing: The pagination doesn't break the page when content is added, resulting in a 3-page printout. The first p ...

Encountering a 405 Error while attempting to perform a search on Twitter

I have been attempting to search Twitter using jQuery, but I am encountering an issue. The response only shows: https://api.twitter.com/1.1/search/tweets.json?q=django 405 (Method Not Allowed) XMLHttpRequest cannot load https://api.twitter.com/1.1/search/ ...

Encountering an error with dynamic routing in Angular 4 when using dynamic components

Upon receiving routing configuration from a server and loading it before the application bootstrap, the config.json file contains the following setup: [{ "path": "dashboard", "component": "SingleComponent", "data": {...} }, { "path": "payment", ...

Using the URL parameter in a jQuery AJAX request

When I try to make an ajax call from a modal window, the request URL doesn't seem to be correct. My webserver is set up to accept URLs like http://localhost/search, but not file:///search. How can I fix this issue? I have posted more details about wh ...

Implementing an event listener on a mesh operation

I tried implementing a function in Three.js to create a sphere and wanted to add an event listener to log the value of textureToShow when it's clicked. However, when I tested it, nothing showed up in the console. Below is the code I used: function cre ...

`How can I customize the appearance of individual selected <v-list-item> across various sub-groups?`

As a newcomer to Vuetify and Vue in general, I am struggling to solve a specific issue. I need to create multiple sub-groups where only one option can be selected within each "parent" list. Consider an array of cats: options:["Crookshanks", "Garfield", " ...

Create a Bootstrap modal that includes a checkbox option to prevent it from appearing again in

I am attempting to display a bootstrap modal upon body load based on a value retrieved from a MySQL database. The bootstrap modal is included in the body and shown successfully depending on the database value using the following code snippet: $results ...

Choose the Hexagonal Surface within the Octahedral Structure in THREE.js

My current project involves working with a geodesic sphere that was initially created using THREE.OctahedronGeometry. I am looking to group the triangular faces into hexagonal faces for easier selection, but I am unsure of the best approach to solving this ...

Leverage the power of Meteor, ReactJS, and MongoDB to trigger actions upon user exiting the

Struggling with creating a matchmaking algorithm that pairs up two users randomly. Can't figure out how to delete the connection stored in a MongoDB collection when one of the users leaves the page. ...

Having trouble generating JSON data within an asynchronous loop using Vuejs and FileReader?

A mechanism is required for users to submit multiple files through a Vue form component. Prior to sending the data to a remote JSON API endpoint, these files need to be processed. An attempt was made to address this by utilizing FileReader and an asynchro ...

Data binding operations being executed concurrently with ajax requests

I am facing an issue with the following HTML structure: <rich:panel id="selectorPanel"> <h:inputText value="#{myBean.field1}" /> <h:inputText value="#{myBean.field2}" /> <h:inputText value="#{myBean.field3}" /> < ...

Encountering the android.os.NetworkOnMainThreadException error when utilizing AsyncTask for parsing JSON data with Gson

When attempting to retrieve and parse JSON data using Gson, I encountered an issue with error message: android.os.NetworkOnMainThreadException I am aware that performing network operations on the main UI thread is prohibited. My code example is as foll ...

PlateJS: Transforming HTML into data

Trying to implement a functionality where clicking on a button retrieves an HTML string. The objective is to have this rich text editor within React-Hook-Form, and upon form submission, the value will be saved as HTML for database storage. Below is the pr ...

What is the best way to store data from my API JSON into my object using Redux and React?

I am having difficulty understanding some concepts in JavaScript and Redux. I am trying to retrieve data from my Redux action, but I seem to be facing an issue with my code. const mapStateToProps = state => { const group = state.groupReducer.group ...