Let's say I have three files: a page that is used for searching data called search, a file that handles requests called controller, and a file that has functions which the controller calls based on what POST parameter is passed. From the search page, I post some data and specify my action (search) via AJAX to the controller. The controller then takes that and calls a function that returns the data (which is inserted into the appropriate place in the DOM) which looks something like this:
<?php
function fetchStudentData($search, $roster) {
//If a user is not logged in or the query is empty, don't do anything
if(!isLoggedIn() || empty($search)) {
return;
}
global $db;
//Placement roster search
if($roster == "placement") {
$query = $db->prepare("SELECT t1.id,
t2.placement_date,
t2.placement_room,
t1.student_id,
t1.student_type,
t1.last_name,
t1.first_name,
t1.satr,
t1.ptma,
t1.ptwr,
t1.ptre,
t1.ptlg,
t1.waiver,
t2.tests_needed,
t2.blackboard_id
FROM student_data AS t1
JOIN additional_data AS t2
ON t1.id = t2.student_data_id
WHERE t2.placement_date = :search
ORDER BY t1.last_name ASC");
$query->bindParam(":search", $search);
$query->execute();
if($query->rowCount() == 0) {
return;
}
echo "<div id='searchHeader'>
<div class='searchSubHead'><em>Placement Roster For $search</em></div>
<br />
<span>Placement Room</span>
<span>Student ID</span>
<span>Student Type</span>
<span>Last Name</span>
<span>First Name</span>
<span>SATR</span>
<span>PTMA</span>
<span>PTWR</span>
<span>PTRE</span>
<span>PTLG</span>
<span>Waiver</span>
<span>Tests Needed</span>
<span>Blackboard ID</span>
</div>";
while($row = $query->fetch()) {
echo "<div id='{$row['id']}' class='placementRosterRecord'>
<span>{$row['placement_room']}</span>
<span>{$row['student_id']}</span>
<span>{$row['student_type']}</span>
<span>{$row['last_name']}</span>
<span>{$row['first_name']}</span>
<span>{$row['satr']}</span>
<span>{$row['ptma']}</span>
<span>{$row['ptwr']}</span>
<span>{$row['ptre']}</span>
<span>{$row['ptlg']}</span>
<span>{$row['waiver']}</span>
<span>{$row['tests_needed']}</span>
<span>{$row['blackboard_id']}</span>
</div>";
}
}
}
?>
This is obviously working very well for me but I wanted to know if there's a better way I should be doing this? Should I be returning the raw data from the database and encoded as JSON and then have my JavaScript take care of creating elements/structure? I see that a lot with various API's but this is something internal to my company and not something that other developers will be using. Is there anything wrong with my approach?