"Encountered an Unspecified Variable Error in executing document

Every time I open my Chrome console, it keeps showing an error message saying "toggleOnlyRelatedPosts is not defined". The script I'm working on doesn't seem to be functioning properly. I've added so many variables that I now feel lost and overwhelmed. Although I thought I clearly defined everything, apparently there is an issue at the document.write line according to Chrome.

This is the script in question:

<script type="text/javascript">
    //<![CDATA[
    function postGrabber(json) {

            // The Magic
            for (var i = 0; i < json.feed.entry.length; i++) {
                for (var j = 0; j < json.feed.entry[i].link.length; j++) {
                    if (json.feed.entry[i].link[j].rel == 'alternate') {
                        var postUrl = json.feed.entry[i].link[j].href;
                        break;
                    }
                }

            // Thumbnail Stuff
            var orgImgUrl = json.feed.entry[i].media$thumbnail.url ? json.feed.entry[i].media$thumbnail.url : 'http://1.bp.blogspot.com/-mxinHrJWpBo/VD6fqbvI74I/AAAAAAAAcn8/LslulDeOROg/s72-c/noimage-chalkboard.jpg';
            var newImgUrl = orgImgUrl.replace('s72-c', 's' + imgSize + '-c');
            var imgTag = '<a class="item-link-post" href="' + postUrl + '"><img class="item-img-thumbnail" src="' + newImgUrl + '" width="' + imgSize + '" height="' + imgSize + '"/></a>';

            var authorName = json.feed.entry[i].author[0].name.$t;
            var authorURL = json.feed.entry[i].author[0].uri.$t;
            var authorOriImgUrl = json.feed.entry[i].author[0].gd$image.src;
            var authorNewImgUrl = authorOriImgUrl.replace('s512-c', 's' + authorImgSize + '-c');
            var authorImgTag = '<a class="item-link-author" href="' + authorURL + '" target="_blank" rel="nofollow"><img class="item-img-author" src="' + authorNewImgUrl + '" alt="' + authorName + '"/></a>';

            var postLabel = json.feed.category[i].term;
            var postLabelUrl = '/-/' + postLabel + '';

            // Standard Stuff
            var postTitle = json.feed.entry[i].title.$t;
            var postCommentCount = json.feed.entry[i].thr$total.$t;

            var postSummary = json.feed.entry[i].summary.$t;
            var entryShort = postSummary.substring(0, '' + summaryLength + '');
            var entryEnd = entryShort.lastIndexOf(" ");
            var postContent = entryShort.substring(0, entryEnd) + '...';

            var postDate = json.feed.entry[i].updated.$t ? json.feed.entry[i].updated.$t : json.feed.entry[i].published.$t;
            var shortDate = postDate.substring(0,10);

            // Let's Make Options Here
            var toggleImg = showImg ? '' + imgTag + '' : '';
            var toggleTitle = showTitle ? '<h1 class="item-title">' + postTitle + '</h1>' : '';
            var toggleSummary = showSummary ? '<p class="item-snippet">' + postContent + '</p>' : '';
            var toggleDate = showDate ? '<span class="item-date">' + shortDate + '</span>' : '';
            var toggleAuthorImg = showAuthorImg ? '' + authorImgTag + '' : '';
            var toggleCommentCount = showCommentCount ? '<span class="item-comment-count">' + postCommentCount + '</span>' : '';


            var toggleOnlyRelatedPosts = showOnlyRelatedPosts ? '' + postLabelUrl + '' : '';

            // The Output
            var itemPost = '<div class="item-post"><div class="item-imgs">' + toggleImg + toggleAuthorImg + '</div>' + toggleCommentCount + '<a class="item-link" href=' + postUrl + '>' + toggleTitle + '</a>' + toggleSummary + toggleDate + '</div>';

            // Let's Write It Down
            document.write(itemPost);
        }
    }
    //]]>
</script>
<script type="text/javascript">
    //<![CDATA[
    var imgSize = 96;
    var summaryLength = 142;
    var authorImgSize = 36;
    var showImg = true; 
    var showTitle = true; 
    var showSummary = true; 
    var showDate = true;
    var showAuthorImg = true;
    var showCommentCount = true;
    var showOnlyRelatedPosts = true;
    document.write('<script type="text/javascript" src="/feeds/posts/summary' + toggleOnlyRelatedPosts + '?orderby=published&amp;max-results=5&amp;alt=json-in-script&amp;callback=postGrabber"><\/script>');
    //]]>
</script>

Answer №1

Within the function postGrabber, the variable toggleOnlyRelatedPosts is initialized. As a result, it remains undefined when you attempt to utilize it in conjunction with document.write.

To access these variables outside of the function, you must declare them at a higher scope level.

Explore the concept of 'scope', as it holds significant importance across various programming languages.

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

Can you explain the significance of triple brackets (e.g. {{{ content }}}) in the context of Javascript/Typescript?

As I delve into the code of a fresh project in which I hope to contribute, I have come across numerous methods defined with triple brackets, like so: deinitialize() {{{ this.destroyed = true; $(window).off("resize", this.resize as () => void); ...

Utilizing React to create an infinite loop, where an onClick event triggers an image change that updates the source of

I'm experiencing an infinite loop in my React application. I'm attempting to include a previous Image and next Image button in the development stage using an image tag. However, when my component loads up, I encounter errors. Does anyone have a ...

Bringing in data from <script> to use in <script setup>

To ensure unique ids for instances of a Vue component, I am using a simple generator to enumerate them. Typically, I would initialize the generator outside of the setup function like this: const idGen = generateIds("component:my-component"); export defaul ...

An easy way to insert a horizontal line between your text

Currently, I have two text responses from my backend and I'm considering how to format them as shown in the design below. Is it possible to automatically add a horizontal line to separate the texts if there are two or more broadcasts instead of displa ...

Unable to utilize the "fs" module within a Three.js application

After utilizing this base code to create an app with Three.js, I attempted to incorporate node's fs module for filesystem interaction. Despite adding const fs = require("fs") in my app.js file, the module could not be located. The error mess ...

The callbacks in NextAuth do not appear to be functioning

I am currently working on implementing authentication with NextAuth in my Next.js app. I've noticed that the callbacks from the GoogleProvider are not being executed. Even after adding a console log statement, I cannot see any output in the console. A ...

What is the best way to organize large amounts of data into an array?

I am currently working on developing a unique version of wordle using javascript and html. In order to do this, I require a comprehensive list of all possible wordle words stored in an array format. Although I have the words listed within a document contai ...

Vuejs - Display multiple dates within one component

I have developed various components (such as tables, selects, etc) that all rely on the same methods to access API information. The main objective is to be able to use these components across different pages of the application in a way that allows for fle ...

Learn how to send a POST request in Python using a saved variable

Having trouble with post requests in Python, encountered this error import requests token='Bearer aslkdjndskgns' endpoint = "https://aap.xyz" phone_number='9177903753951' data = {"number":phone_number} datas = str(data) headers={ ...

What is the best way to create a function that shifts a musical note up or down by one semitone?

Currently developing a guitar tuning tool and facing some hurdles. Striving to create a function that can take a musical note, an octave, and a direction (up or down), then produce a transposed note by a half step based on the traditional piano layout (i. ...

Using PHP to globally access a JavaScript object named

I have a collection of CSS attributes stored in a MySQL database that are accessed using PHP. These attributes need to be accessible to JavaScript once the page has finished loading. To achieve this, I loop through each row and create a JavaScript object ...

What is the best way to choose the initial element in every group using jQuery?

If we have the following HTML input: <p>A</p> <p>B</p> <p>C</p> <div>D</div> <p>E</p> <p>F</p> <p>G</p> We can select B, C, F and G using the following code: $('p + ...

Error encountered while executing jest tests due to an unexpected import token

Despite trying numerous solutions and suggestions on Stack Overflow, I am still unable to resolve the issue at hand. I recently discovered jest and attempted to use it by following a tutorial on testing React components with jest from DZone. However, when ...

Discover a corresponding object within an array

I am currently dealing with an array of objects in Javascript where I need to verify if a certain value exists within any object and return the corresponding id. The issue arises when using the some() function as it only seems to match the first object. T ...

ChessboardJs: JavaScript Boards Function Properly on Initial Use Only

Update: The page code can be accessed via my page URL. I'm unsure where the issue lies. Your assistance is appreciated. Issue: Initially, when clicking on the chess puzzles page, everything works fine. However, upon re-clicking from the homepage, th ...

sending a pair of variables via jQuery and AJAX

Having difficulty posting two variables using ajax and jquery when a button on a confirm window is pressed. Each variable can be displayed separately, but not both at the same time. UPDATE - Issue resolved. I overlooked including a necessary file. My mist ...

What is the reason behind postgres' error message: "operator does not exist: json ? unknown

Trying to execute this specific query against my postgres database, I encountered a challenge: select distinct offer_id from offers where listing_id = 2299392 group by offer_id having not bool_or(status in ('Rejected', 'Draft&ap ...

Updating a numeric field in Mongoose by a percentage of its current value

Looking for a way to reduce prices of items in Mongoose. { name:"itemname", price: 30 } I want to apply a 10% reduction to the price, but $inc and $mul won't work for this scenario. {$mul: {price:0.10}} This code would reduce the price to 10% of t ...

Error encountered while executing ExpressJs function that was converted to a promise

Understanding how errors are handled in promises can be a bit tricky, especially for someone new to promises like myself. I'm trying to make the most of them, but I'm not quite there yet. Here is the code snippet I'm working with: app.list ...

Tips for effectively handling the auth middleware in react.js by utilizing LocalStorage

After making a call to the authentication API, the plan is to save the authentication token in LocalStorage and then redirect to a dashboard that requires token validation for entry. However, an issue arises where the authentication token isn't immedi ...