I'm using PHP to dynamically generate badges, and load them in my page via ajax. I then try to add functionality to these badges using jQuery, but the jQuery isn't acting on elements that are generated by the PHP.
I figured that maybe the jQuery and bootstrap needed to be imported in the PHP script in order for it to work. No luck.
Whether the jQuery is generated in PHP, or it is generated in the HTML file, it doesn't work with elements that are generated by PHP and loaded via ajax.
The badges load fine, it's just that jQuery isn't able to do anything with them. Not assigning function, nothing.
I'm out of ideas. You guys?
PHP FILE
if($tagpeople){
// FIND TAGS
// TRYING TO ADD BOOTSTRAP AND JQUERY HERE, BECAUSE I'M OUT OF IDEAS
$tags = "
<head>
<!-- Bootstrap 4 CSS -->
<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css' integrity='sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm' crossorigin='anonymous'>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>
<!--Bootstrap 4.5.2-->
<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css'>
<script src='https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js'></script>
<!--FONT AWESOME-->
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css'>
</head>
<script>
$('.form-tag').click(function(){
alert('badge clicked');
})
</script>
";
// PULLING INFO FROM DATABASE TO GENERATE BADGES (OR, "TAGS")
$findtags = "SELECT * FROM pTags";
$alltags = mysqli_query($dragonden, $findtags);
// GENERATE HTML FOR EACH BADGE
while($tagDAT = mysqli_fetch_array($alltags))
{ $tags .=
"
<div style='display:none;'>
<input value='".$tagDAT[1]."' id='".$tagDAT[0]."' name='".$tagDAT[1]."' type='checkbox' class='ptag form-check-input form-check-inline'>
</div>
<div class='form-check m-1 p-0' style='display:inline-block;float:left;'>
<h6>
<label class='form-check-label text-capitalize badge badge-dark badge-pill' for='".$tagDAT[0]."'>".$tagDAT[1]."</label></h6>
</div>
"; }
// SEND BADGES TO THE HTML PAGE
$data = array();
array_push($data, $tags);
print json_encode($data);
}
JQUERY SCRIPT IN HTML FILE
$.ajax({
type: "POST",
dataType: "json",
url: "q-svc-agr-builder.php",
data: { tagpeople:1 },
success: function(data){
$("#ptags").html(
data[0]
);
}
}).fail(function(XMLHttpRequest, textStatus, errorThrown)
{
$("#ptags").html("Status: " + textStatus + "<br>Error: " + errorThrown);
});