Bind data to dynamically created HTML elements using Ajax jQuery.

Mohammed Imtiyaz Apr 17, 2020

Demo

Bind data to dynamically created HTML elements using Ajax jQuery

Binding data to HTML elements is quite easy using Ajax jQuery. Let’s take an example of an online point of sale system where adding products to invoice varies from customer to customer.

Usually binding data to HTML select undergoes a process of sending the request to the server. It’s ok if you have a single HTML select but in our scenario we are creating multiple rows. Sending request to server whenever a new HTML select is created is not a good idea. To overcome this, we can take a different approach to improve the performance.

In this approach, we will send the request to server to bind data to the HTML select when the page loads. While appending the data to HTML select, we will store the data in an array which helps in binding the data to dynamically created HTML select.

First create a global variable "prodData" that can be accessible throughout the page.

To bind data to "ddlProdList" for the first time when the page loads, call LoadProductList() method. This will retrieve data from the database.


/* prodData will store the list of products (product name & product price) 
   whenever the data is binded to HTML Select (ddlProdList) for the first time. 
*/
var prodData = [];

$(document).ready(function () {
    LoadProductList();
});

Data retrieved from the database is binded to "ddlProdList" and simultaneously the data is stored in the "prodData" as well.


/* Populate product list from database. */
function LoadProductList() {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "Default.aspx/PopulateProductList",
        dataType: "json",
        async: "true",
        beforeSend: function () {
            /* Progress loader can be displayed here... */
        },
        success: function (result) {
            $("select[name^=ddlProdList]").append("");
            $.each(result.d, function (key, value) {

                $("select[name^=ddlProdList]").append($("").val(value.prodId).html(value.prodName).attr("data-prod-price", value.prodPrice));

                prodData.push({
                    'prodId': value.prodId,
                    'prodName': value.prodName,
                    'prodPrice': value.prodPrice
                });
                var jsonProdData = JSON.stringify({ prodData: prodData });
            });
        },
        failure: function (response) {
            alert(response.responseText);
        },
        error: function (response) {
            alert(response.responseText);
        }
    });
}

Now here comes the main purpose behind this approach. Whenever a new table row (new product) is added, we need to bind the list of product to "ddlProdList". Instead of sending the request to server to retrieve data, we will bind the data using the data stored in the array variable "prodData".

This approach will save the time in sending and receiving request from the server and improves the performance.


/* Add new empty rows. */
var counter = 0;
$("#btnNewItem").on("click", function () {
    LoadStaticProductList();
});

/* Populate product list from static array. */
function LoadStaticProductList() {

    if (prodData.length > 0) {
        $("select[name^=ddlProdList]").append("");
        for (var i = 0; i <= prodData.length; i++) {
            $("select[name^=ddlProdList]").append($("").val(prodData[i].prodId).html(prodData[i].prodName).attr("data-prod-price", prodData[i].prodPrice));
        }
    }
    else {
        LoadProductList(userId);
    }
}