There are many ways to load dynamic data using jQuery. For example,
In this tutorial, we are going use the second method to load dynamic data into a list box. Let us see an example to get UserType and DateOfBirth information of multiple users. The user information form will be,
When we click on the Add User icon at the bottom right corner, a new wizard will be appended with UI.
In this example, we should go with the following steps to implement dynamic data loading using jQuery.
We should create UI for getting UserType and DateOfBirth from the user. The code will be,
form.php
<div class="phppot-container tile-container">
<div class="row">
<label>User Type:</label> <select name="userType[]"
class="userType">
</select>
</div>
<div class="row">
<label>Date of Birth:</label> <input type="text"
name="dateAry[]" class="userDOB" />
</div>
</div>
Now, it’s time to set dynamic data into the UI. Let us have an array of user type. We should iterate over a loop to get options for UserType list box.
These options are loaded dynamically based on the match found with the specified selectors while invoking jQuery HTML(). The code will be,
index.php (UI HTML and CSS includes)
<?php
$listOptions = '';
$userType = array(
"Visiter",
"Member",
"Admin"
);
foreach ($userType as $k) {
$listOptions .= "<option value='" . $k . "'>" . $k . "</option>";
}
?>
<html>
<head>
<title>Load Dynamic Data using jQuery</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<link rel="stylesheet" type="text/css" href="css/form.css" />
</head>
<body>
<div id="target"></div>
<div id="button-position">
<div onClick="setDynamicUI('form.php');" id="circle-img">
<img src="plus-circle.svg" title="Add" alt="More User" />
Add More
</div>
<img src="spinner.svg" id="loader" alt="missing">
</div>
</body>
</html>
Foreach loop creates HTML <option>…</option> tags and put it into a PHP variable $listOptions. This variable will be sent to jQuery to load this dynamic content into all elements having specified selectors.
index.php (jQuery script to add-more dynamic input)
<script src="https://code.jquery.com/jquery-3.6.1.min.js"
integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ="
crossorigin="anonymous"></script>
<link rel="stylesheet"
href="https://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="https://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
function setDynamicUI(view) {
$("#loader").show();
$("#circle-img").hide();
$("<div>").load(view, function() {
$("#target").append($(this).html());
$(".userType").html(<?php echo json_encode($listOptions); ?>);
$('.userDOB').datepicker({
changeMonth: true,
changeYear: true
});
$("#loader").hide();
$("#circle-img").show();
});
}
$(document).ready(setDynamicUI("form.php"));
</script>
Since we are getting DateOfBirth from the user, we are triggering jQuery date picker on date box click event.
Download