Executing FB.api() functions within an underscore template

Despite the underscore template documentation suggesting that this should be possible, I am experiencing difficulties with it. When I try to execute the template, it does not return any output.

<% FB.api('/me', function(response){ %>
<%= response.name %>
<% }); %>

Answer №1

This template is completely valid; the compiled JavaScript version is shown below:

function(obj) {
    var __p = '';
    var print = function() { __p += Array.prototype.join.call(arguments, '') };
    with(obj || {}) {
        __p += '\n';
        FB.api('/me', function(response) { 
            __p += '\n' + response.name + '\n';
        }); 
        __p += '\n';
    }
    return __p;
}

Everything looks good so far. By the way, you can view the JavaScript code for the template by accessing the source property of a compiled Underscore template:

var t = _.template(raw_template);
console.log(t.source);

However, there's a catch. The issue arises because the FB.api call is asynchronous. Here's what actually happens:

  1. The template is compiled and executed.
  2. FB.api is called asynchronously.
  3. The template returns HTML which is added to the DOM.
  4. Some time passes.
  5. Finally, the callback from Facebook is triggered.
  6. At this point, it's too late to update the template content since it has already been inserted into the DOM.

To resolve this, you need to restructure your logic. Move the FB.api call outside of the template like this:

var t = _.template(...);
FB.api('/mu', function(response) {
    var html = t({ response: response });
    // Add the html to the DOM here
});

This change ensures that the template is only used once all the necessary data is available.

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

Managing PHP Arrays in Ajax Responses

When making an AJAX request to a PHP file, I use the following code: $.post({ url: "manage.php", dataType: "JSON" }, { firtname: John, lastname: edwin }, function(data){ $("#persons").html(data[0]) }); The PHP file then returns data ...

problems with loading jquery and jquery UI conditionally

This code snippet demonstrates how to load jQuery from a CDN, falling back to a local version if needed: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> <script>!window.jQuery && document.write( ...

Is it possible to prevent users from editing the content in TinyMCE wysiwyg?

Utilizing a TinyMCE WYSIWYG editor, I am able to send content to my SQL database and retrieve it back on the same page. Instead of creating additional pages to handle this process, I decided to keep everything compact and efficient by incorporating all fun ...

Is it possible to locate a particular value within a nested array?

Help Needed: I'm working with an array that contains a nested array and I need to loop through it to locate a specific value. arr = [['123456','234567'], ['345678']]; specificValue = '123456'; I am looking for ...

Tips for safely storing data in local storage using Angular 5

How can I securely store data in local storage, such as encrypting and decrypting the local storage data to prevent manipulation by other users? If it's not possible with local storage, what are alternative methods for client-side data storage? I&apo ...

Assistance required with Jquery logic for managing different divs with individual triggers. Ensure only one div is open at a time and close all others when a new one is opened

http://jsfiddle.net/nicktheandroid/ZSvHK/ I am facing some challenges with my current code and would appreciate any suggestions for improvement. Here are the issues I am encountering: I have a set of divs, each with its own trigger button. Only one menu ...

What is the best approach for integrating HTML and JavaScript code into Flutter mobile platforms?

For the past 4 months, I've been immersing myself in Flutter without any prior experience in Javascript. My goal is to utilize the Soundcloud HTTP API to create a user-interactive app. However, I've hit a roadblock when it comes to integrating JS ...

Encountering a surprise Illegal Token JS Error

I am encountering a persistent "Unexpected Token ILLEGAL" error while attempting to run the script on the page after it has been registered. StringBuilder str = new StringBuilder(); str.Append("<script type='text/javascript&apos ...

Concentrate on Managing Text Input Fields in Zend Form

I designed a form using Zend Form and want the focus to be on a text area within the form when the page loads. I attempted to use JavaScript for this purpose, but it only briefly shows the focus before removing it again, preventing any typing. I considere ...

What is the best way to set a default function in a mongoose schema?

After spending quite a few hours trying to resolve this issue, I have finally turned to Stack Overflow for help. The problem I'm facing is with the promise pending errors on a specific field where I need to set a default value. Here's the code s ...

Using Meteor: Sharing a variable among all methods in Meteor

Just dipped my toes into the world of Meteor and managed to create a simple turn-based multiplayer game. When player 2 joins the game, I update the Game collection using a Meteor.method. However, when I try to retrieve that update in another Meteor.method ...

Leveraging JavaScript along with the jQuery library and API to showcase information related to

Hey there! I have been working on this API that shows upcoming concerts, but I'm struggling to display the images associated with each concert. I've tried using for loops to iterate through the objects, and it seems like every sixth element has ...

The request for http://localhost:3000/insert.js was terminated due to a 404 (Not Found) error

As someone new to web development, I am currently tackling a project where I'm having trouble loading the Javascript file insert.js. The HTML document upload.html resides in the public folder, while the Javascript file is located in the main folder. I ...

Is there a way to assign a unique scrollTop value for a specific scrollspy location?

I have a custom script that tracks the current position within a menu and applies an active class to it. However, I require specific rules for the ID contact_form. Specifically, I need to add 1000px to the scrollTop value for that particular ID location. ...

Unable to bring in Vue component from NPM module

Hello there, I recently developed my own npm package for a navigation bar and I need to incorporate it into my main codebase. Currently, I am utilizing vue @components but I am struggling with integrating the imported component. If anyone has insight on h ...

AngularJS allows for setting the rate value using the jQuery Raty plugin

I am attempting to implement the jquery raty plugin for star rating using angularjs. To achieve this, I have created a custom directive as shown below: app.directive("ngStars", function() { return { restrict: 'A', ...

What is the best way to organize arrays with various combinations?

I am trying to rearrange the elements in 3 arrays: ["s","m"], ["Red","Black"], ["1", "2"]. My desired arrangement is as follows: ["s","Red","1"], ["s"," ...

Insert a picture into a table using the ajax response in Laravel

When attempting to add an image to a table, I am encountering an issue where the src path is not displaying any results. if(data ){ txt += '<tr><td>'+data.groupname[i].group_name+'</td><td class="text-right"&g ...

The font-face declaration is not functioning properly within the CSS code, causing the browser to fail in displaying the

@font-face { font-family: BYekan; font-style: normal; font-weight: normal; src: url(../resources/BYekan.eot); /* IE9 Compat Modes */ src: url(../resources/BYekan.woff) format('woff'), url(../resources/BYekan.woff2) ...

Integrate birthday validation using the validate.js library in a React application

After reading the article linked here, I incorporated it into my app. My next step is to include a date validation to ensure that the person is over 18 years old. I am currently struggling with understanding where and how to incorporate the parse and for ...