What is the best way to eliminate the occurrence of the word 'undefined' from the cycle output?

Can anyone assist with solving this issue?

The webpage on JSFIDDLE displays 4 news containers, but an 'undefined' string appears before the first news container. I am looking to remove that 'undefined' string.

Here is the HTML code:

<div class="banners__wrap-article" id='sk_wrap_82630'></div>

And here is the JavaScript code:

xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
        document.getElementById('sk_wrap_82630').innerHTML = '<div class="banners__smi2"> \
            <div class="banners__smi2__header"><span class="banners__smi2__header-text">News</span></div> \
            ' + cycleItems() + ' \
            </div> \
            <div class="banners__smi2"> \
                <div class="banners__smi2__header"><span class="banners__smi2__header-text"></span></div> \
            </div>';                
    }
}

function cycleItems(){
    var items = "";
    var massive = JSON.parse(xmlhttp.responseText);

    for (var i = 0; i <= 3; i++) { 
        items += constructItem(massive.news[i].url, massive.news[i].img, massive.news[i].title);
    };

    return items;
}

function constructItem(url, img, title){
    var item;

    return '<div class="banners__smi2__item"> \
                <a href="' + url + '" class="banners__smi2__link"> \
                    <img class="banners__smi2__img" src="' + img + '" alt="" /> \
                    <span class="banners__smi2__title">' + title + '</span> \
                </a> \
            </div>';
}

Answer №1

To start off, make sure to set the variable items to an empty string within the function cycleItems(). Here's how:

 var items = '';

Feel free to refer to this example on jsfiddle for further clarification.

JSFiddle Example

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

A straightforward interval-based Ajax request

I've recently delved into the world of Ajax and jQuery. Just yesterday, I embarked on creating a simple ajax request for a form that sends a select list value to a PHP script and retrieves data from a database. Things are going smoothly so far! Howev ...

Make the current tab the active tab with the help of AngularJS

I have a set of five tabs that are functioning correctly. However, when I refresh the page, the active tab reverts back to its default state instead of staying in its current active state. Can anyone help me identify where I may be making a mistake? Here ...

The Bootstrap validator triggers the form submission only after the second click

When I click on the submit button, I am attempting to submit a form that has its default action prevented and first checks a condition before proceeding. Below is the code snippet: $('#payment-form').bootstrapValidator({ live: 'dis ...

Merge two nested JSON arrays by overriding the values of JSON A with those of JSON B

There are two JSON arrays that need to be compared. If the "id" property in Json A matches the "id" property in Json B, then override the values of the properties in Json A with the values of the properties in Json B. Here is the JSON A Array: { "com ...

Cease the use of bi-directional data binding on an Angular directive

One way I've been attempting to send information to a directive is through the following setup: <ui-message data="{{app}}"></ui-message> In my controller, this is how I define it: app.controller("testCtrl", function($scope) { $scope.a ...

"Eliminate a specified range of characters from a string using JavaScript

I am currently working on a JavaScript function that will remove specific characters from a string. I have tried various methods such as `string.slice()`, `string.substr()`, and `string.substring()`, but what I really need to do is remove everything before ...

Guide on obtaining the total value from a JSON Array in Angular 2 using TypeScript

I received a JSON response which includes carts values with different amounts. "carts": { "value": [ { "Amt": 40 }, { "Amt": 20.25 }, ...

Requesting data from a server using JavaScript/Ajax/Flash technologies over

Here is the code snippet I am currently using: swfobject.embedSWF("/Content/open-flash-chart.swf", "my_chart", "750", "300", "9.0.0", "expressInstall.swf", ...

Is there a way to halt or end an interval within a function triggered by useEffect()?

I am currently working on a countdown timer script using react.js. The timer displays a 3 or 5 seconds countdown before starting, with data for these countdowns coming from another component. I am facing an issue with controlling the main countdown timer ...

The process of accessing JSON array values in iOS

I have a JSON dictionary, and I need to extract specific values such as NAME, SECTION, CLASS, IMAGE, DOB from it. I am also looking for guidance on how to retrieve the image using the provided code snippet. Can someone assist me in displaying the image a ...

Exploring the process of extracting specific data from a dynamic JSON response and seamlessly transferring it to another request

After receiving a .json file as a response from an API, I need to parse it and extract a specific parameter to pass as input to the next request. How can this be accomplished using Katalon? When attempting to use: response = JSON.parse("response.json"); ...

Sequelize JS - Opting for the On clause in join operations

Seeking guidance on selecting the appropriate ON clause for a join. I am working with two tables - packages and users. The package table contains two fields/columns (owner_id, helper_id) that serve as foreign keys to the same users table. My goal is to per ...

How to Handle Empty Input Data in JQuery Serialization

Having an issue with a form that triggers a modal window containing another form when a button is clicked. The second form includes an input field and send/cancel buttons. The goal is to serialize the data from the modal form and send it to a server using ...

What is the best way to show instructions immediately upon receipt of a response?

I'm currently working on developing a website similar to ChatGpt using the OpenAI API for GPT. However, there is a delay in generating responses with GPT taking a few seconds. As a result, my code only displays the instruction once the response from G ...

The node.js application was unable to locate the '../HMS/server/models/user' file

Hi there! I'm currently working on an application with a folder structure as shown below. I want to use the following line in my passport.js file: var User = require('../server/models/user'); However, I encountered the error below after tr ...

Chrome browser not triggering first click event for AJAX jQuery checkbox

My Java application is built with Struts 1.1, utilizing actions, forms, and business objects. To enhance performance, I have integrated AJAX into my code to fetch data quickly and display it in a grid. However, I encountered an issue where clicking on a ch ...

Create a knockout computed observable that relies on an ajax request and doesn't return a boolean value upon successful completion

I have created a knockout pureComputed observable that determines the validity of an account number. The process involves several steps: Checking if the field is empty (returns false). Verifying if the account number has changed from the initial loa ...

Tips for incorporating jQuery to load Rails form partials and submit them as a single form:

Trying to improve the readability of my Rails HTML code, I decided to extract certain portions into partials and then used jQuery to render these partials. However, a problem arose where the form seems disconnected after implementing this approach. It appe ...

Is there a way to send a preexisting JSON object to an OPTION in jQuery or JavaScript?

What is the best way to pass a preexisting JSON as a data value in an HTML option tag? I am aware that I can manually pass individual variables like this: <option data-value='{"name":"rajiv","age":"40"}'>a</option> However, if I ha ...

Website experiencing issues with moderating Facebook comments

I recently added a Facebook comments box to my website in the footer. Although it is visible, I am unable to moderate it. Furthermore, the comments are not showing up in the comments queue panel at https://developers.facebook.com/tools/comments. I am us ...