Looping through a JSON array and encoding it using the `

I am looking to retrieve data from the database using AJAX and populate a 'select' tag with that data. Each name should be displayed in its own 'option'. Here is the code snippet:

Index.php:

<label>Select:</label>
<select id="users"></select>

JS:

$(document).ready(function() {
setInterval(function() {
    $.get("frombase.php", function(data) {
        data = JSON.parse(data);
        for (var id in data) {
            $("#users").empty();
            $("#users").append("<option value='"+ id +"'>"+ data[id] +"</option>")
        }
    });
}, 1000);

});

And frombase.php:

$sql = "SELECT * FROM `users`";
$result = mysqli_query($db, $sql);

$name = array();

while ($row = mysqli_fetch_assoc($result)) {
$name[] = $row['name'];
}
echo json_encode(array("name" => $name));

mysqli_close($db);

View the outcome below (I do not need this)

https://i.stack.imgur.com/boEnL.jpg

(Please excuse any errors in my English as I am using Google Translate)

Answer №1

If I were to tackle this issue, I would approach it as follows:

JavaScript Solution:


    $(document).ready(function() {
        $.ajax({
            url: 'fetchdata.php',
            type: "POST",
            dataType: "json",
            success: function(data){
                $("#results").empty();
                $(data['items']).each(function(index, value){
                    $("#results").append("<option value='"+ value['id'] +"'>"+ value['name'] +"</option>");
                });
            },
            error: function(){
                alert('There was an error communicating with the server');
            }
        });
    });

PHP Code:


    $db = 'YOUR DATABASE CONNECTION';
    $stmt = $db->prepare("SELECT id, name FROM items");
    $stmt->execute();
    $stmt->bind_result($id, $name);

    while ($stmt->fetch()) {
        $result[] = array('id' => $id, 'name' => $name);
    }
    
    $response['items'] = $result;
    $response = json_encode($response);     
    $db->close();
    echo $response; 

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

Invoke a function from a neighboring component using React hooks

Is there a way to call a function from another component using props or context? I've attempted to do this using props and context, but I'm getting confused as I need to pass an actual function with parameters. The goal is to invoke the handleS ...

Iterating Through an Array using Foreach Loop in PHP after using json_decode

I am having some issues with a foreach loop that I'm trying to run through an array. Specifically, I keep coming across the error message "Undefined index: text". Here is the code snippet in question: $tweets = json_decode($response,true); foreach ( ...

unable to submit form using angular and express

I am encountering an issue with a post request in AngularJS to express. The HTML form on the client side is defined as follows: <div ng-controller="LoginCtrl"> <form ng-submit="login()"> <div> <label>Username</lab ...

What steps can be taken to resolve an HTTP Error 500 when encountering it in a PDO execute

I've been attempting to run a query using php PDO, but the execute method is triggering an HTTP ERROR 500. $query = "select * from job_t where title like '%:title%' and salary>=:salary"; $st = $conn->prepare($query); $st->bindParam ...

PHP: Communicating Data with JavaScript

What if my PHP script requires some time to complete its operations? How can I keep the client updated on the progress of the operation, such as during a file download where the estimated time and data size need to be communicated? In PHP, calculating all ...

Encountering issues with the setValue function in Nightwatch

Currently, I am in the process of setting up a new Nightwatch project to automate a basic Google search page. The assertion for searchbox present on page is successful, but I am facing difficulties performing any mouse or keyboard actions on the elements ( ...

Developing a TypeScript NodeJS module

I've been working on creating a Node module using TypeScript, and here is my progress so far: MysqlMapper.ts export class MysqlMapper{ private _config: Mysql.IConnectionConfig; private openConnection(): Mysql.IConnection{ ... } ...

Verify the placement within the text box

Are there methods available in JavaScript or any JavaScript framework to determine the position within a textbox? For example, being able to identify that figure 1 is at position 2 and figure 3 is at position 3. Figure 1 Figure 2 ...

The gzseek function appears to be exceeding the file's size limit

For the past two years, I have been dealing with an odd issue when determining the size of files, especially gz zip compressed files. Despite trying various workarounds, I haven't found an ideal solution. The problem lies in the fact that gzseek() alw ...

Incorporating a delay into looped HTTP requests while effectively utilizing Promise.all to track their completion

Greetings! In my current project, I am trying to introduce a 50ms delay before each subsequent HTTP request is sent to the server. Additionally, I aim to incorporate a functionality that triggers after all requests have been successfully made. To better e ...

Is there a way to illuminate a complete row by simply hovering over a span within one of the columns?

If I want to change the background-color of a div with classes "row" and "highlightThisRow" when hovering over a span with the class "fromThisSpan", how can I achieve that? In a list, there are multiple rows with several columns. The span in question is l ...

Sending parameter and ng-click to the angular directive

I am looking for a way to transfer data from HTML to the directive, allowing the directive to be clickable using ng-click. How can I pass the parameter of the link function to the template? app.directive("hello", function(){ return { restrict: "E" ...

What is a more efficient method for verifying the value of an object within an array that is nested within another object in JavaScript?

Is there a more efficient way to check for an object in an array based on a property, without having to go through multiple checks and avoiding potential errors with the ? operator? /** * An API returns a job object like: * { id: 123, name: 'The Job ...

Is it no longer possible to export static pages in Next.js 14?

I'm currently experiencing a problem where my CSS styles are not being exported when I try to convert my project into static HTML pages. Here is the configuration in my next.config.js file: ** @type {import('next').NextConfig} */ const next ...

extracting an empty value from this variable

When I click on an anchor tag using this operator, the value appears blank. I have multiple divs with the same class, so I used the .each() function, but I can't figure out where I'm going wrong. The desired output is that when I click on one of ...

Transitioning React Hover Navbar Design

I'm currently revamping a click-to-open navbar into a hover bar for a new project. I have successfully implemented the onMouseEnter and onMouseLeave functions, allowing the navbar to open and close on mouse hover. However, I am facing an issue with ad ...

Choosing from a variety of tr elements

I'm working with a table in HTML that has about 100 rows. I would like to apply different colors to specific groups of rows, such as making rows 1-10 red and rows 20-40 blue. Using nth-child seems like an option, but it can get quite verbose if I nee ...

Reveal or conceal information with a dropdown menu feature

I am attempting to implement a feature where the image file upload section is hidden or displayed based on the selection made in a dropdown list. If the user selects option "2", the image upload section should be hidden. Conversely, if they choose option " ...

Issue found in Bootstrap-Multiselect plugin: The dropdown menu appears beneath the outer container when overflow-y is applied

My experience with using Bootstrap-Multiselect and encountering an issue where the dropdown disappears when the outer container has overflow-y: scroll and a max-height has prompted me to seek solutions. I am looking for a way to ensure that the dropdown is ...

"Upon completing the AJAX file upload, the response message fails to appear on the

I am currently diving into the world of ajax and attempting to create a file uploader using ajax in codeigniter. The issue I am facing is that although the file gets successfully uploaded to the /uploads folder, the response message (alert or image preview ...