The basics of AJAX are simple. You send a request to be processed on the server and it sends back a response. When responding to an AJAX request, anything output by the server program (stuff that would normally go to the browser screen) is sent back as the response.
Here's a simple example (using data from the DB in my tutorial) which accepts a teacher_id, sends it in a request, and recieves back the data for that teacher thne displays it.
<?php
require 'db_inc.php';
$db = pdoConnect('jointute'); // my cuton connection function - use your connection code
//******************** PROCESS AJAX REQUESTS *********************
//
//
if (isset($_GET['ajax'])) {
if ($_GET['ajax']=='teacher') {
exit(json_encode(getTeacher($db, $_GET['tid'])));
}
else {
exit('INVALID');
}
}
//
// Functions
//
function getTeacher($db, $id) {
$res = $db->prepare("SELECT t.fname
, t.lname
, d.deptname as dept
FROM teacher t
JOIN department d USING (dept_id)
WHERE teacherid = ?
");
$res->execute([ $_GET['tid'] ]);
$row = $res->fetch();
if ($row) {
return $row;
}
else return ['fname'=>'NOT FOUND', 'lname'=>'', 'dept'=>''] ;
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<title>Example</title>
<meta charset='utf-8'>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type='text/javascript'>
$().ready( function() {
$("#find").click( function() {
var tid = $("#tid").val()
$.get(
"", // specify processing file on server (in this case it's same file)
{"ajax":"teacher", "tid":tid}, // data to send in request
function(resp) { // handle the response
$.each(resp, function(k,v) {
$("#"+k).val(v)
})
},
"JSON" // response type
)
})
})
</script>
<style type='text/css'>
body {
font-family: calibri, sans-serif;
font-size: 12pt;
}
div {
margin: 16px;
padding: 8px;
border: 1px solid gray;
}
label {
display: inline-block;
background-color: black;
color: white;
width: 120px;
padding: 8px;
margin: 1px 8px;;
}
</style>
</head>
<body>
<div>
<label>Teacher ID (1-20)</label>
<input type='number' id='tid' value='0'>
<button id='find'>Find</button>
</div>
<div>
<label>First name</label><input type='text' id='fname' value='' readonly><br>
<label>Last name</label><input type='text' id='lname' value='' readonly><br>
<label>Department</label><input type='text' id='dept' value='' readonly>
</div>
</body>
</html>