Anticipate the arrival of the getJSON response

Currently, I am working on a script that utilizes Yahoo's YQL within a web application. This script is designed to scan through a text paragraph, identify references, and display them as popups within the text. Everything works smoothly until I reach the point where I need to iterate through each reference with the class "verso". Upon receiving the response, all the references are appended to the last element of the list.

Below is a simplified version of the JavaScript code:

            var url="";
        var version = "RVR1960";
        var verso = "";

        $("div.post-body").find(".verso").each(function(i){
            $resultado = null;
            verso = $(this).text();
            url = "http://query.yahooapis.com/v1/public/yql?" + "q=select%20*%20from%20html%20where%20url%3D%22"+
                encodeURIComponent("http://www.biblegateway.com/passage/?search=" + verso +
                "&version=" + version) + "%22&format=xml'&callback=?";
            $pasaje = $(this);

            $.getJSON(url,function(data){
                if(data.results[0])
                {
                    $resultado = null;
                    $resultado = $(data.results[0]).find("div.result-text-style-normal:first");
                    $resultado.find("h5, div, a").remove();
                    $("<div class='cita'><span class='left'>“</span>"+
                        $resultado.html()+
                        "<p align='right'><b>"+verso+"</b></p>"+
                        "<span class='right'>”</span></div>").appendTo($pasaje);
                }
                else
                {
                    $resultado = $("<p>Pasaje no encontrado.</p>");
                }
            });
        });

Here is an example of the HTML structure used:

<div class="post-body"><b class="verso">John 3:16</b><b class="verso">Matthew 11:28</b><b class="verso">John 1:1</b></div>

I would greatly appreciate any assistance or suggestions provided.

Answer №1

Great news! I made some modifications to your code and now it's up and running smoothly. Enjoy!

var url="";
var version = "ESV";
var passage = "";

$("div.post-body > b.passage").each(function(i){
    result = null;
    passage = $(this).text();
    url = "http://query.yahooapis.com/v1/public/yql?"+"q=select%20*%20from%20html%20where%20url%3D%22"+encodeURIComponent("http://www.biblegateway.com/passage/?search="+passage+"&version="+version)+"%22&format=xml'&callback=?";

    $.getJSON(url,function(data){
        if(data.results[0])
        {
            result = null;
            result = $(data.results[0]).find("div.result-text-style-normal:first");
            result.find("h5, div, a").remove();
            $("<div class='quote'><span class='left'>&ldquo;</span>"+result.html()+"<p align='right'><b>"+passage+"</b></p>"+"<span class='right'>&rdquo;</span></div>").appendTo($("div.post-body > b.passage")[i]);
        }
        else
        {
            result = $("<p>Passage not found.</p>");
        }
    });
});

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

Firestore/Javascript error: FirebaseError - The data provided is invalid for the DocumentReference.set() function. An unsupported field value of 'undefined'

I keep encountering this error Error creating user: FirebaseError: Function DocumentReference.set() called with invalid data. Unsupported field value: undefined (found in field diabetesComplication) After some investigation, I realized that the iss ...

What is the best way to align a series of divs vertically within columns?

Struggling to find the right words to ask this question has made it difficult for me to locate relevant search results. However, I believe a picture is worth a thousand words so...https://i.stack.imgur.com/LfPMO.png I am looking to create multiple columns ...

Retrieve the unique identifier of a single post from a JSON file within a NuxtJS project

Is there a way to retrieve the unique post id data from a JSON file in NuxtJS? created() { this.fetchProductData() }, methods: { fetchProductData() { const vueInstance = this this.$axios .get(`/json/products.json`) ...

Navigating using Backbone Marionette URL to Server Endpoint

I need to implement client-side validation to check if the user is logged in, and if not, redirect them to the sign-in page. The issue is that the sign-in page exists outside of my Backbone Marionette app. Is there a way in Marionette, Backbone, jQuery, or ...

Generating a three-level unordered list using arrays and for-loops in JavaScript/JSON

Are there more efficient ways to achieve the desired results from this JSON data? Can someone assist me in understanding why it is working and if it can be optimized for cleanliness? <div id="accordion" class="display-data"> ...

Tips on saving every query outcome in a separate array and delivering it back to the controller upon completion

I am currently facing an issue where I receive data in a function from my controller, and inside my model function, I need to retrieve results using a query with a dynamic value of channel. The channel ID will be coming from each checkbox on my HTML view ...

"Discover the step-by-step process of transforming an input field value into a checkbox with

I've been experimenting with creating a To-Do list using HTML, CSS, and Javascript. I've managed to capture the input field value in a fieldset so far. However, my goal is to find a way to transform the input field value from the textfield into a ...

Sending information to a Flask application using AJAX

Currently, I am working on transferring URLs from an extension to a Flask app. The extension is able to access the current URL of the website. I have set up an AJAX request to connect to Flask, and the connection is successful. However, when trying to send ...

Comparison of performance between serializing an object to indexedDB and using JSON.stringify

I am curious about the efficiency differences in terms of browser/CPU/memory between using JSON.stringify for serialization versus writing an object to an object store in indexedDB. The context for this question is optimizing the process of writing an obj ...

Variations between <div/> and <div></div>

When using Ajax to load two divs, I discovered an interesting difference in the way they are written. If I write them like this: <div id="informCandidacyId"/> <div id="idDivFiles"/> Although both divs are being loaded, only one view is added ...

The JQuery function fails to execute following a successful Ajax request

I recently ran into an issue with my Ajax call. Here's the code snippet in question: $("#start-upload-btn").click(function(){ $.ajax({ type: "post", url: "", data: { newProjectName: $('#project-name') ...

Efficiently incorporate a set of fields into a form and automatically produce JSON when submitted

The optimal approach for dynamically adding a set of fields and generating JSON based on key-value pairs upon form submission. <div class="container"> <div class="col-md-4"> <form method="POST" id="myform"> <div class="f ...

Manipulate Attributes in Javascript

Having an issue here - I'm trying to use JavaScript to set some attributes. for(i=0;i<div_navi.childNodes.length;i++){ if(div_navi.childNodes[i].nodeName =="SPAN"){ div_navi.childNodes[i].setAttribute("onclick","g ...

Implementing JavaScript to showcase a list extracted from an API dataset

I'm currently undertaking a project where I am integrating an API from a specific website onto my own webpage. { "data": [{ "truckplanNo":"TCTTV___0D010013", "truckplanType":"COLLECTION", " ...

Blogger's homepage URL obtained using JSON data

Please note: I don't have a background in programming. I'm making an effort to learn as much as possible. As I was reading (and later experimenting with) the solution to this query, it dawned on me that having the same information in JSON form ...

A guide on displaying JSON response data in Angular JS with the help of ng-repeat

I am attempting to display the values of a specific JSON in the correct order. Here is how my JSON is structured : { "A":[{"id":"21","name":"Andrea"},{"id":"22","name":"Apple"}], "B":[{"id":"21","name":"Baby"},{"id":"22","name":"Bali"}], "C":[{"id":"21"," ...

Using jsPlumb to Access an Element After a "Mouseup" Event has Completed

$(document).on('mouseup', '.agent-wrapper', function(info){ console.log(info); // Everything is working fine console.log(this); }); .agent-wrapper represents an element-wrapper for all jsPlumb objects. $(document).on(' ...

The function WebForm_DoCallback is not recognized

Encountering an error where WebForm_DoCallback is undefined. UPDATE WebForm_DoCallback("AccountPageControl1", "FileSave~" + fileName, CVFileSavedServerResponse, null, null, true); function CVFileSavedServerResponse(param, context) { } Why isn't ...

How to Retrieve Video Length using AJAX in the YouTube API

I have been working on a script to fetch the duration of a YouTube video using its id. Here is the code snippet I've written: var vidID = ""; var vidData; var vidDuration; function getResponse() { $.getJSON( "https://www.googleapis.c ...

Combining various postponed JavaScript file imports in the HTML header into a single group

I've been facing an issue with my code structure, particularly with the duplication of header script imports in multiple places. Every time I need to add a new script, I find myself manually inserting <script type="text/javascript" src=&q ...