Ajax Control Demo
GET Array:
Array ( )
Operation
Click on any of the control structures above to see the ajax operation work. Note, there is NO Browser web page refresh.
Description of the AJAX Operation
- The index.php file (below) is the file that is called by a Browser when initally accessed.
- The index.php file also loads the axaj.js code that preforms the background server communications.
- The index.php file also includes the ajax-slave.php file (below). Both files are seen as a single web page by the Browser.
- The ajax-slave.php file is loaded by an include() statement that exist inside a <div id="myspan"> div inside the index.php file.
- The ajax.js file (below) is triggered through the ajax-slave.php file via javascript onclick(), onblur(), and onchange() triggers.
- Any of these javascript triggers can send a GET message to the ajax.js file.
- After receiving a message, the ajax.js file sends a request to the server and then waits for the server to respond.
- After receiving a response from the server, the ajax.js file then fires an action to the ajax-slave.php file.
- That action causes a portion of the web page to refresh between the "myspan" div.
- The ajax-slave.php file then reloads and operates on the GET message.
- As a result, that portion of the web page (i.e., ajax-slave.php) changes.
- The complete action mimics the operation of a normal desktop application.
The three files that accomplish this feat follow:
1) CODE for index.php
<?php // index.php
include('includes/header.php');
?>
<h1>Ajax Control Demo</h1>
<div id="myspan"> <!-- start of myspan ajax operation-->
<?php include('ajax-slave.php'); ?>
</div> <!-- end of myspan ajax operation-->
<?php
include('includes/footer.php');
?>
2) CODE for ajax-slave.php
<?php // ajax-slave.php
$mytext = isset($_GET['mytext']) ? $_GET['mytext'] : null;
$mytextarea = isset($_GET['mytextarea']) ? $_GET['mytextarea'] : null;
$myradio = isset($_GET['myradio']) ? $_GET['myradio'] : 1;
$mycheck1 = isset($_GET['mycheck1']) ? $_GET['mycheck1'] : null;
$mycheck2 = isset($_GET['mycheck2']) ? $_GET['mycheck2'] : null;
$mycheck3 = isset($_GET['mycheck3']) ? $_GET['mycheck3'] : null;
$mycheck4 = isset($_GET['mycheck4']) ? $_GET['mycheck4'] : null;
$mycheck5 = isset($_GET['mycheck5']) ? $_GET['mycheck5'] : null;
$myselect = isset($_GET['myselect']) ? $_GET['myselect'] : 1;
$url = 'ajax-slave.php';
$c = 'CHECKED';
$s = 'SELECTED';
?>
<br>
<fieldset>
<legend>AJAX Examples:</legend>
<label for="mytext">Text</label>
<input type="text" id="mytext" name="mytext" value="<?php echo($mytext); ?>"
onblur="get(this.parentNode, '<?php echo($url); ?>');">
<br><br>
<label for="mytextarea">Textarea</label>
<textarea rows="4" cols="50" id="mytextarea" name="mytextarea"
onblur="get(this.parentNode, '<?php echo($url); ?>');">
<?php echo($mytextarea); ?>
</textarea>
<br><br>
<label for="radio">Radio</label>
<input type="radio" id="myradio" name="myradio" value="1"
onclick="get(this.parentNode, '<?php echo($url); ?>');"
<?php if ($myradio == 1)
{
echo($c);
} ?>> 1
<input type="radio" id="myradio" name="myradio" value="2"
onclick="get(this.parentNode, '<?php echo($url); ?>');"
<?php if ($myradio == 2)
{
echo($c);
} ?>> 2
<input type="radio" id="myradio" name="myradio" value="3"
onclick="get(this.parentNode, '<?php echo($url); ?>');"
<?php if ($myradio == 3)
{
echo($c);
} ?>> 3
<br><br>
<label for="checkbox">Checkbox</label>
<input type="checkbox" id="mycheck1" name="mycheck1" value="1"
onclick="get(this.parentNode, '<?php echo($url); ?>');"
<?php if ($mycheck1 == 1)
{
echo($c);
} ?> > 1
<input type="checkbox" id="mycheck3" name="mycheck2" value="2"
onclick="get(this.parentNode, '<?php echo($url); ?>');"
<?php if ($mycheck2 == 2)
{
echo($c);
} ?> > 2
<input type="checkbox" id="mycheck3" name="mycheck3" value="3"
onclick="get(this.parentNode, '<?php echo($url); ?>');"
<?php if ($mycheck3 == 3)
{
echo($c);
} ?> > 3
<input type="checkbox" id="mycheck4" name="mycheck4" value="4"
onclick="get(this.parentNode, '<?php echo($url); ?>');"
<?php if ($mycheck4 == 4)
{
echo($c);
} ?> > 4
<input type="checkbox" id="mycheck5" name="mycheck5" value="5"
onclick="get(this.parentNode, '<?php echo($url); ?>');"
<?php if ($mycheck5 == 5)
{
echo($c);
} ?> > 5
<br><br>
<label for="myselect">Select</label>
<select id="myselect" name="myselect" onchange="get(this.parentNode, '<?php echo($url); ?>');">
<option value="1"
<?php if ($myselect == 1)
{
echo($s);
} ?> >1
</option>
<option value="2"
<?php if ($myselect == 2)
{
echo($s);
} ?> >2
</option>
<option value="3"
<?php if ($myselect == 3)
{
echo($s);
} ?> >3
</option>
<option value="4"
<?php if ($myselect == 4)
{
echo($s);
} ?> >4
</option>
</select>
</fieldset>
<div class="clear">
</div>
<pre>
<?php
echo('<br>GET Array:<br>');
print_r($_GET);
?>
</pre>
3) CODE for ajax.js
// Modern AJAX GET using fetch
async function makeRequest(url, parameters) {
try {
const response = await fetch(`${url}${parameters}`, {
method: 'GET',
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const result = await response.text(); // Assuming response is text
document.getElementById('myspan').innerHTML = result;
} catch (error) {
console.error('There was a problem with the request:', error);
alert('There was a problem with the request.');
}
}
function get(obj, url) {
let getstr = "?";
Array.from(obj.childNodes).forEach(node => {
if (node.tagName === "INPUT") {
if (node.type === "text") {
getstr += `${encodeURIComponent(node.name)}=${encodeURIComponent(node.value)}&`;
}
if (node.type === "checkbox") {
getstr += `${encodeURIComponent(node.name)}=${node.checked ? encodeURIComponent(node.value) : ""}&`;
}
if (node.type === "radio" && node.checked) {
getstr += `${encodeURIComponent(node.name)}=${encodeURIComponent(node.value)}&`;
}
}
if (node.tagName === "SELECT") {
getstr += `${encodeURIComponent(node.name)}=${encodeURIComponent(node.options[node.selectedIndex].value)}&`;
}
if (node.tagName === "TEXTAREA") {
getstr += `${encodeURIComponent(node.name)}=${encodeURIComponent(node.value)}&`;
}
});
// Send the request
makeRequest(url, getstr);
}
/*
Key Updates from my older code.
1. fetch API:
fetch is now the preferred way to make HTTP requests. It's promise-based and handles responses more cleanly than XMLHttpRequest.
Provides a modern, concise syntax and better error handling with try...catch.
2. Simplified DOM Traversal:
Replaced for loop with Array.from and forEach, which improves readability.
3. URL Encoding:
Added encodeURIComponent to properly encode query parameters, preventing issues with special characters.
4. Error Handling:
Enhanced error reporting with console.error and improved alert messages for better debugging.
Benefits:
• Easier to maintain and extend.
• More readable and modern syntax.
• Works across all modern browsers without legacy compatibility concerns.
*/