I want to show the data from PHP if one of the object is selected. This is the HTML code I wrote but it doesn't work. I kind of know the reason is either because the PHP will get executed once, so it won't display anything after that. Or the PHP part down below did not receive the software object at all. Should I have a Javascript that does the display work? Is that necessary?
<select name="software" onchange="showSoftware(this.value)">
<?php foreach ($softwareCollection as $software): ?>
<option value="<?php echo $software ?>">
<?php echo $software->date?>
</option>
<?php endforeach; ?>
</select>
<script>
function showSoftware(software) {
jQuery.ajax({
type: "POST",
data: {software: software},
success: function(data) {
console.log(data);
}
});
}
</script>
<?php if (isset($_POST['software'])): ?>
<?php foreach ($software->links as $link): ?>
<tr>
<td>
<?php echo $link->title; ?>
</td>
<td>
<?php echo $link->url; ?>
</td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
Another way to solve it with single html file is to cache all the options and data to the front end like:
<script>
require(['jquery'], function($) {
jQuery(document).ready(function($) {
/*
* Cache the softwareCollection
*/
var softwareCollection = [];
<?php foreach ($softwareCollection = $this->getSoftware() as $software): ?>
var links = [];
var softwareId = '<?php echo $software->id ?>';
var softwareDate = '<?php echo $software->date->date?>';
<?php foreach ($software->links as $link): ?>
links.push({
title: '<?php echo $link->title ?>', description: '<?php echo $link->description?>',
url: '<?php echo $link->url ?>'
});
<?php endforeach; ?>
softwareCollection.push({id: softwareId, date: softwareDate, links: links});
<?php endforeach; ?>
softwareCollection.sort((a, b) => (a.date < b.date));
const $this = $('select[name=software]');
for (var i = 0; i < softwareCollection.length; i++) {
$this.append(
'<option value=\"' + softwareCollection[i].id + '\">' + softwareCollection[i].date + '</option>'
);
}
}
}
</script>
PHPin it's own opening and closing brackets? Why not just do<?php if(isset($_POST['software'])){ foreach ($software->links as $link){ ?> <!-- html !--> <?php } } ?>?<?php $software ?>should be either<?php echo $software; ?>or<?= $software ?>.$softwareobject to the function so that I didn't useechoas it tries to convert the object to string and gives error. I modified the code a bit to pass the$software->id, and find the object according to it but still doesn't work.$softwarewas an object, you will need to changeecho $softwareintoecho $software->xxx(without knowing your object structure I can't say whatxxxshould be but possibly id?).