jqueryajaxasp.net-coreasp.net-ajax

Data Listing with Ajax (Only Last Data Coming)


I am developing a project with ASP.NET Core. I want to pull data from the database with Ajax without posting the page. But only one and the last saved data comes. I can see other data in the console.

Can you help me? Thanks,

<tr>
    <td class="border-bottom-0">
        <p id="getTaskTitle" class="fw-semibold mb-1l"></p>
    </td>
</tr>
$("#btnGetTask").click(function () {
            $.ajax({
                contentType: "application/json",
                dataType: "json",
                type: "GET",
                url: "/TaskList/ListTask/",
                success: function (func) {
                    let getList = jQuery.parseJSON(func);
                    let _getTaskTitle = document.getElementById("getTaskTitle")
                    $.each(getList, (i, value) => {
                        _getTaskTitle.innerText = `${value.TaskTitle}`
                        console.log(value.TaskTitle);
                    });

                }
            });
        });

It does not return any error.


Solution

  • Your loop replace the value of inner text with recent value, so why it's show only last value.

    Instead of add innerText in each loop create string and append once.

    Example:

    var htm = "";
    let _getTaskTitle = $("#getTaskTitle");
    $.each(getList, (i, value) => {
      htm += `${value.TaskTitle}`
      //console.log(value.TaskTitle);
    });
    _getTaskTitle.text(htm); //or _getTaskTitle.html(htm)
    

    Update: based upon comment for break line between ajax response.

    // Your data from ajax request. It's only sample data for example.
    var getList = [{
        TaskTitle: "red",
        value: "#f00"
      },
      {
        TaskTitle: "green",
        value: "#0f0"
      },
      {
        TaskTitle: "blue",
        value: "#00f"
      }
    ];
    var htm = "";
    let _getTaskTitle = $("#getTaskTitle");
    var dt = [];
    $.each(getList, (i, value) => {
      dt.push(`${value.TaskTitle}`);
    });
    htm = dt.join("<br>");
    _getTaskTitle.html(htm); 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="getTaskTitle"></div>

    Note: Don't miss match jQuery and JavaScript.