What could be causing the issue where only the latest data is being shown

When I use ajax to retrieve data from my database, the console.log displays all the results correctly, but in my HTML, only the last result is shown. What could be causing this issue? Any help would be appreciated! Thanks!

Please keep your response simple as I am new to this :)

Here is my code:

HTML

<div class="mI">            

        <section>
                <div class="pM" id="m1"></div>
            </form>
        </section>


        <aside class="mBI">
            <div class="mT">
                <p id="m2"></p>
            </div>

            <p id="mG"></p>
            <p style="margin-top:-8px" id="m3"></p>

        </aside>    
</div>

JAVASCRIPT

$(document).ready(function() {
    "use strict";
    function connect2MO() {
        $.ajax({
            url: "tes.php",
            type: "GET",
            //data:"",
            dataType: "json",
            //async:false,
            success: function(data) {
                $.each(data, function() {
                    var mP = this.p;
                    var mT = this.t;
                    var mG = this.g;

                    console.log(mP);
                    console.log(mT);
                    console.log(mG);


                    $('#m1').html('<img src="p/' + mP + '"/>');
                    $('#m2').html(mT);
                    $('#m3').html(mG);
                });
            },
            error: function connect2MO() {
                alert('error loading MO');
            }
        });
    }

    if (window.attachEvent) {
        window.attachEvent('onload', connect2MO);
    } else if (window.addEventListener) {
        window.addEventListener('load', connect2MO, false);
    } else {
        document.addEventListener('load', connect2MO, false);
    }
});

PHP

<?php
        include ('session_start.php');        
        include ('db_connect_MO.php');

    $sql = mysqli_query($con, "SELECT * FROM mo ORDER BY mRD");
    $row = mysqli_fetch_array($sql);

        while ($row = mysqli_fetch_assoc($sql)) 

        {           
            $test[]= array( 
                            'p'=> $row['mP'],
                            't'=> $row['mT'],
                            'g'=> $row['mG'],
                        );
        }

        header('Content-Type: application/json');
        echo json_encode ($test);

        //detailed error reporting
        if (!$sql) 
        {
            echo 'MySQL Error: ' . mysqli_error($db);
        exit;

        }
?>

The php snippet below shows what I'm aiming for with ajax.

<?php while ($row = mysqli_fetch_assoc($sql)) { ?>

<div class="mI">            

        <section>
               <div class="pM"><img src="p/<?php echo $row["mP"];?>" alt=""/></div>
        </section>

        <aside class="mBI">
            <div class="mT">
                <p><?php echo $row["mT"];?></p>
            </div>

            <p id="mG"></p>
            <p style="margin-top:-8px"><?php echo $row["mG"];?></p>

        </aside>    

</div>

<?php } ?>

Answer №1

      var data = [{'p': 'p1', 't':'t1', 'g': 'g1'},{'p': 'p2', 't':'t2', 'g': 'g2'},{'p': 'p3', 't':'t3', 'g': 'g3'}];

          $.each(data, function() {

            $.each(this, function(key,value) {

              var display = '<div>'+ key +' = ' +value+ ' </div>';

              $('body').append(display);

            });

          });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

For your code you can do it like this

var data = [{'p': 'p1', 't':'t1', 'g': 'g1'},{'p': 'p2', 't':'t2', 'g': 'g2'},{'p': 'p3', 't':'t3', 'g': 'g3'}];

    $.each(data, function() {

    var html = '<hr>' +

    '<div class="mI">' +     

        '<section>' +
                '<div class="pM" >' + this.p + '</div>' +
            '</form>' +
        '</section>' +

        '<aside class="mBI">' +

            '<div class="mT">' +
                '<p>' + this.t + '</p>' +
            '</div>' +

            '<p></p>' +
            '<p style="margin-top:-8px" id="m3">' + this.g + '</p>' +

        '</aside>' +    
    '</div>';

    $('body').append(html);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Answer №2

Switch this:

     $('#m1').html('<img src="p/' + mP + '"/>');
     $('#m2').html(mT);
     $('#m3').html(mG);

which merely replaces the values with this that appends:

      $('#m1').html($('#m1').html() + '<img src="p/' + mP + '"/>');
      $('#m2').html($('#m2').html() + mT);
      $('#m3').html($('#m3').html() + mG);

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

Exploring TypeORM: Leveraging the In() function within @ManyToMany relationships

There are two main characters in my story: Hero and Villain (their profiles are provided below). How can I utilize the Encounter() method to identify all instances where the Hero interacts with the Villain based on an array of Villain IDs? I am seeking a ...

Developing an Android application that utilizes PHP to return JSON encoded data

I have a situation where I am outputting JSON encoded data at the end of a PHP file on my server using the code "echo json_encode($response);" When this PHP file is accessed directly from a browser, the encoded data appears in the browser instead of being ...

How to resolve undefined callback when passing it to a custom hook in React Native

I'm facing an issue with passing a callback to my custom hook: export default function useScreenshotDetection(onScreenshot) { useEffect(() => { ... onScreenshot(); ... }, []); } Strangely, the callback is not being detected ...

Combining Mongoose OR conditions with ObjectIDs

After querying my Team schema, I am receiving an array of ids which I have confirmed is correct. The issue seems to lie in the fact that both home_team and away_team are ObjectIDs for the Team Schema within my OR statement. Team.find({ 'conferenc ...

Fetching Results from Promise

Repeatedly, this question has been asked in various forms but I still do not understand: I have a resolved promise with a value. When I console.log this object, everything appears to be functioning correctly. I can see exactly what I want to see. My setu ...

Detecting when users stop scrolling in Angular 5

Is there a way to toggle visibility of a div based on user scrolling behavior? I'd like the div to hide when the user scrolls and reappear once they stop. I've attempted to achieve this effect using @HostListener, but it only seems to trigger wh ...

The final thumbnail fails to appear in the visible display (react-responsive-carousel)

I am currently facing an issue with displaying a series of images using react-responsive-carousel. When the images exceed a certain size causing the thumbnail section to become scrollable, the last thumbnail is always out of view. Although I have impleme ...

Ways to fix vulnerabilities found in an NPM audit

Upon conducting an NPM audit, I found 5 critical issues. To address 4 of them, I attempted to update @storybook/addon-essentials & @storybook/react, as they were marked as "patched in >=x.x.x", indicating that the latest versions should have resolved t ...

Having difficulty accessing a PHP ajax post request

I've scoured every resource but can't seem to find a solution to this issue. I'm in the process of writing an ajax script, however, I am struggling to retrieve the correct value from the POST request. Here is the code I have so far: <t ...

Problems with Key Presses in Form Verification

Yesterday evening, our supervisor called me to report an issue with our app. He mentioned that when he tried to log in using a dummy password, the validation was successful. It seems that clicking on the mouse to authenticate the password was working corr ...

Ajax is incapable of achieving success or encountering failure

I'm having some trouble displaying search results on the view using AJAX. The action retrieves JSON data and sends it, but for some reason the AJAX call is not receiving the data. $(function () { $("#btnSearchForUser").click(function () { ...

pass user identification by using a link using php and MySQL

In my table of items, there is an option for users to delete or restore each item, using a special PHP file called 'delete.php'. print "<td>"; if ($row['deleted'] == 'y') { print "<a href='delete.php?id=2'& ...

Tips for activating multiple CSS animations when scrolling

I am currently working on a project that involves multiple CSS animations. However, I am facing an issue where these animations only occur once when the page initially loads. I would like them to trigger every time the user scrolls past them, regardless of ...

Split the output of IPTC.php into two separate variables

Presented below is the code snippet I am currently working with: <?php require_once('IPTC.php'); $iptc = new Image_IPTC('001.jpg'); print_r($iptc); ?> The output of the code is as follows: Image_IPTC Object ( [_sF ...

Tips on placing a button at the bottom of the AppBar and keeping it fully responsive

I am attempting to place my login and log out buttons at the end of the AppBar. When I try forcing it with marginLeft: '70%',, it works but only on large resolutions. On smaller resolutions, the buttons go out of place. Here is an example of forc ...

Transferring information from JavaScript to PHP

I am trying to send both the data and text that are within a single DIV tag using JavaScript into PHP values. However, I am encountering an issue with the following code: <html> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jq ...

"Although all error messages are functional in Postman, they are not appearing correctly on the frontend client

I am currently developing a website using React and Node. While testing my register and login functionality in Postman, I encountered an issue where the error message for login (e.g., user doesn't exist, username or password incorrect) is not displayi ...

Is the on-error event not functioning properly in the <img> tag?

I am currently utilizing VueJS to develop the front-end of a project and encountered an issue with the image tag when loading images. Template <div class="items" transition="fade" v-for="item in list"> <img :src="item.logoPath" @error="replac ...

Is there a way to dynamically refresh the options in a select dropdown using jQuery?

I'm facing an issue with updating the options in a select element. Here is how my current select element looks: <select id="productId"> </select> Below is the jQuery code I am using: ... if (data.success) { var items = []; $.ea ...

Link scripts can sometimes cause issues with node.js

Greetings! I have successfully created a client-side SPA using vanilla-router. However, my Node.js server sometimes encounters an error when attempting to load a linked script. Uncaught SyntaxError: Unexpected token '<' This error only oc ...