Ajax Control Demo


AJAX Examples:



1 2 3

1   2 3   4   5

 
    
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 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
    &nbsp;
    <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
    &nbsp;
    <input type="checkbox" id="mycheck4" name="mycheck4" value="4"
           onclick="get(this.parentNode, '<?php echo($url); ?>');"
        <?php if ($mycheck4 == 4)
            {
            echo(
$c);
            } 
?> > 4
    &nbsp;
    <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">&nbsp;
    </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.
 */