Troubleshooting a minor JavaScript loop problem

I am facing an issue with my script that retrieves data from a database. Currently, when the search() function is called by clicking a button, only one result is displayed in a new div. How can I ensure that a new div is created for each result found, rather than just displaying the first row?

function search()   {
    var xhr2 = new XMLHttpRequest();
    xhr2.addEventListener ("load", view);
    var reg = document.getElementById("type").value;
    xhr2.open("GET", "getresults.php?type=" + reg);
    xhr2.send();
}
function view(e, resulthtml)    {
    var array = JSON.parse(e.target.responseText);
    for (var count=0; count<array.length; count++)
    {
    var id = array[count].id;
    var username = array[count].username;
    var srcpath = array[count].srcpath;
    var title = array[count].title;
    var type = array[count].type;
    var postcode = array[count].postcode;
    var description = array[count].description;
    var price = array[count].price;
    var phone = array[count].phone;
    var lat = array[count].lat;
    var lon = array[count].lon;

    resulthtml +=          "<div class='col-md-4'>"
                + "<div class='thumbnail'>"
                + "<img id='a' class='a' alt='300x200' src='" + srcpath + "'>"
                + "<div class='caption'>"
                + "<h3>"
                + description
                + "</h3>"
                + "<p>"
                + "£" + price + ""
                + "</p>"
                + "<p>"
                + "Contact number:"
                + "</p>"
                + "<p>"
                + "<input type='submit' value='Contact seller' onclick='search()'/>"
                + "</p>"
                + "</div>"
                + "</div>"
                + "</div>"

    }
    document.getElementById("row").innerHTML = resulthtml;
}   

</script>

Answer №1

Make sure to initialize resulthtml as an empty string outside the loop instead of overwriting it on every iteration.

In addition, consider moving some of the operations outside of the loop to optimize performance, particularly the string concatenation:

var item, id, username, srcpath, title, type, postcode, description, price, phone, lat, lon,
  resulthtml = '',
  pre = "<div class='col-md-4'><div class='thumbnail'><img id='a' class='a' alt='300x200' src='",
  inner1 = "'><div class='caption'><h3>",
  inner2 = "</h3><p>£",
  post = "</p><p>Contact number:</p><p><input type='submit' value='Contact seller' onclick='search()'/></p></div></div></div>";

for (var count=0; count<array.length; count++)
    {
    item = array[count];
    id = item.id;
    username = item.username;
    srcpath = item.srcpath;
    title = item.title;
    type = item.type;
    postcode = item. postcode;
    description = item. description;
    price = item.price;
    phone = item.phone;
    lat = item.lat;
    lon = item.lon;

    resulthtml += pre + srcpath + inner1 + description + inner2 + price + post;

    }

Answer №2

It is not advisable to

document.getElementById("row").innerHTML = resulthtml;

This action will overwrite the existing innerHTML content of the element with id #row. A better approach would be:

document.getElementById("row").innerHTML += resulthtml;

By using this method, you are adding resulthtml to the current innerHTML string, or you can also utilize:

document.getElementById("row").appendChild(resulthtml);

Both methods achieve the same result. The choice between the two ultimately comes down to personal preference.

Answer №3

Cheers for the help! Seems like a minor issue after all.

<script type="text/javascript">

function fetchResults() {
    var xhr = new XMLHttpRequest();
    xhr.addEventListener("load", display);
    var searchTerm = document.getElementById("query").value;
    xhr.open("GET", "fetchdata.php?query=" + searchTerm);
    xhr.send();
}

function display(e, resultHTML) {

resultHTML = "";

var data = JSON.parse(e.target.responseText);
for (var index = 0; index < data.length; index++) {

    var id = data[index].id;
    var name = data[index].name;
    var imageUrl = data[index].imageUrl;
    var description = data[index].description;
    var price = data[index].price;
    var contact = data[index].contact;

    resultHTML += "<div class='col-md-4'>"
                + "<div class='thumbnail'>"
                + "<img src='" + imageUrl + "' alt='Product Image'>"
                + "<div class='caption'>"
                    + "<h3>" + name + "</h3>"
                    + "<p>Price: £" + price + "</p>"
                    + "<p>Contact number: " + contact + "</p>"
                    + "<p><input type='submit' value='Contact Seller' onclick='fetchResults()' /></p>"
                + "</div>"
                + "</div>"
            + "</div>"

}
document.getElementById("resultsRow").innerHTML = resultHTML;
}   

</script>

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

Top method for creating a checkbox filter to toggle the display of elements depending on various data-* attributes

I am currently working on creating a checkbox filter that will display or hide elements based on multiple data attributes assigned to those elements. Despite my attempts, I have not been able to achieve the desired filtering outcome. You can view a basic ...

What are the steps to implement an audio stream in a JavaScript React application?

I have been working on integrating a web dialer system into my JavaScript NextUI React app. After making some progress, I can successfully dial and hear my voice through the phone. However, I am encountering an issue where I cannot hear the other person sp ...

Step-by-Step Guide: Crafting a Non-Ajax Popup Chat Application

Recently, I created a unique dating website with a one-to-one chat feature similar to Facebook. However, I implemented this using the ajax technique and the setInterval function in JavaScript for regular updates. Upon reflection, I believe that this appr ...

What is the best way to retrieve the value of a custom attribute from a dropdown list using either JavaScript or jQuery?

I have a dropdown list on a web form and I need to have a 'hidden' variable for each item in the list that can be retrieved using the onchange event on the client side. To achieve this, after databinding the dropdownlist, I am setting a custom at ...

Using Double Equal in a JavaScript For Loop

I'm struggling to comprehend why utilizing a double equals (or even a triple equals) in the condition of a for loop doesn't function as expected. Consider this example: for (i = 1; i == 5; i++){ console.log(i) } When I replace == with <= ...

Refreshing an Angular datatable using promises - reload directive

I am currently using angular-datatables along with promises and everything is working smoothly. I have various actions that can be performed on each record (using angular $http resource) such as changing a status or similar tasks. However, I find that I n ...

When the "x" close icon is clicked, the arrow should toggle back to 0 degrees

I've been tackling the challenge of creating an accordion and I'm almost there. However, I'm facing an issue where the arrow doesn't return to its original position after clicking the close "x" icon. The toggle works fine but the arrow ...

Tips for configuring page-specific variables in Adobe DTM

Although I have integrated Adobe Analytics for tracking on my website, I am facing difficulty in properly defining the variables. This is how I attempted to define the variable: var z = new Object(); z.abc = true; z.def.ghi = true Despite following the ...

Develop a unique Kotlin/JS WebComponent featuring custom content

I am trying to create a custom tag using Kotlin that includes default content. While the example I found works well, I am having trouble adding default content (such as an input element) inside the custom tag. After attempting various approaches, I have o ...

Setting up a secure HTTPS server using Node.js and Express.js

Currently in the process of setting up a HTTPS server using Node.js and Express.js. This is what I have so far: const filesystem = require('fs'); const express = require('express'); const server = express(); const http = require(&apos ...

execute an ASPX.VB function using AJAX

Here is my query: I am trying to invoke a specific method from the code-behind file of an asp.net webform. Below is my jQuery (Ajax) function: function LoadPayments(_page) { var cliente = 245328; $.ajax({ type: "POST", url: "Pay ...

Tips for repairing a button using a JavaScript function in an HTML document

I am currently working on extracting titles from body text. To achieve this, I have created a button and linked my function to it. The issue I am facing is that when I click on the button, it disappears from its original position. I intend to keep it in pl ...

Implementing React hooks to efficiently remove multiple items from an array and update the state

Looking for help on deleting multiple items from an array and updating the state. I have selected multiple items using checkboxes, which are [5, 4, 3]. My goal is to remove all these items from the array based on their ids and then update the state accordi ...

Passing Selectize.js load callback to a custom function

I set up selectize.js to gather configuration options from html data attributes. One of the configurations involves specifying a js function for custom data loading (not just simple ajax loading). Everything was working smoothly until I tried running an as ...

Explore the Wikipedia API play area by searching based on the user's input

Having trouble searching Wikipedia based on user input. Initially, I suspected a cross-domain issue, but I believe .ajax should resolve that. You can view the codepen here: http://codepen.io/ekilja01/pen/pRerpb Below is my HTML: <script src="https:// ...

Challenges with incrementing in Jquery's each loop and setTimeout

http://jsfiddle.net/fxLcy/ - an example showcasing the use of setTimeout. http://jsfiddle.net/fxLcy/1/ - this demo does not include setTimeout. Although all elements are correctly positioned, I am in need of that delayed animation =/ My goal is to arrang ...

Tips for using jQuery to create a delete functionality with a select element

I'm relatively new to utilizing jquery. I decided to tackle this project for enjoyment: http://jsbin.com/pevateli/2/ My goal is to allow users to input items, add them to a list, and then have the option to select and delete them by clicking on the t ...

Changing the value of a form input name after a $scope.$watch event is activated

In my AngularJS 1.4 project, I have a form input element where I am attempting to dynamically set the name attribute. <input type="email" name="{{ctrl.name}}" class="form-control" id="email" ng-minlength="5" required> The assignment of the name att ...

What is the best way to display a notification on the screen when a user fails to select an option from a checkbox in PHP?

I'm currently tackling a form project where I need to trigger an alert if the user hasn't selected any options from a checklist. Despite scouring various resources for solutions, my lack of JavaScript coding skills has left me at a standstill. He ...

"Unique AJAX feature for manual, customized one-time payment subscriptions for adding items to cart

Hello, I am currently working on manually ajaxing this process: <a href="/cbg-gummies?add-to-cart=55337&convert_to_sub_55337=0" class="testing"> Add to cart </a> The purpose of this is to add a one-time purchase option ...